FileController.java 7.83 KB
package vion.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.date.TimeUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.net.url.UrlEncoder;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vion.dto.FileInfoDTO;
import vion.model.Contract;
import vion.model.FileInfo;
import vion.service.IFileService;
import vion.vo.FileInfoVO;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    private final IFileService fileService;
    private final Converter converter;

    @Value("${fileUrl:}")
    private String fileUrl;

    @GetMapping("/files")
    @SaCheckPermission(value = "file:list", orRole = "admin")
    public Page<FileInfoVO> getFiles(FileInfoDTO data) {
        var wrapper = new MPJLambdaWrapper<>(converter.convert(data, FileInfo.class))
                .selectAll(FileInfo.class)
                .selectAs(Contract::getContractNo, FileInfoVO::getContractNo)
                .selectAs(Contract::getName, FileInfoVO::getContractName)
                .leftJoin(Contract.class, Contract::getId, FileInfo::getContractId)
                .eq(ObjUtil.isNotNull(data.getStoreId()), FileInfo::getStoreId, data.getStoreId())
                .eq(ObjUtil.isNotNull(data.getSourceId()), FileInfo::getSourceId, data.getSourceId())
                .eq(ObjUtil.isNotNull(data.getContractId()), FileInfo::getContractId, data.getContractId())
                .eq(ObjUtil.isNotNull(data.getSourceType()), FileInfo::getSourceType, data.getSourceType())
                .in(CollUtil.isNotEmpty(data.getSourceTypeList()), FileInfo::getSourceType, data.getSourceTypeList())
                .like(StrUtil.isNotBlank(data.getContractNo()), Contract::getContractNo, data.getContractNo())
                .orderByDesc(FileInfo::getCreateTime);

        return fileService.selectJoinListPage(Page.of(data.getPageNum(), data.getPageSize()), FileInfoVO.class, wrapper);
    }

    @GetMapping("/file/download")
    @SaCheckPermission(value = "file:download", orRole = "admin")
    public ResponseEntity<FileSystemResource> download(Long id) {
        var fileInfo = fileService.getById(id);
        var file = FileUtil.file(fileInfo.getUrl());

        if (!FileUtil.exists(file)) {
            return ResponseEntity.notFound().build();
        }
        FileSystemResource resource = new FileSystemResource(file);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + UrlEncoder.encodeAll(file.getName(),
                StandardCharsets.UTF_8).replace("+", "%20"));

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }

    @DeleteMapping("/file/{id}")
    @SaCheckPermission(value = "file:remove", orRole = "admin")
    public String remove(@PathVariable(name = "id") Integer id) {
        FileInfo file = fileService.getById(id);
        FileUtil.del(file.getUrl());
        fileService.removeById(id);
        return "文件删除成功";
    }

    @PostMapping("/file/{id}")
    @SaCheckPermission(value = "file:edit", orRole = "admin")
    public String updateFile(@PathVariable Long id, @RequestBody FileInfoDTO dto) {
        Assert.notNull(dto.getUpdFlag(), "更新标识符不能为空!");
        return fileService.lambdaUpdate()
                .eq(FileInfo::getId, id)
                .set(ObjUtil.isNotNull(dto.getSourceType()), FileInfo::getSourceType, dto.getSourceType())
                .set(ObjUtil.isNotNull(dto.getContractId()), FileInfo::getContractId, dto.getContractId())
                .update() ? "修改成功" : "修改失败";
    }

    @PostMapping("/file/formFileUpload")
    @SaCheckPermission(value = "file:form:upload", orRole = "admin")
    public String uploadFile(FileInfoDTO dto, @RequestParam(name = "file") MultipartFile infile) throws IOException {
        String filename = FileNameUtil.mainName(infile.getOriginalFilename()) + "_" +
                TimeUtil.format(LocalDateTime.now(), "yyyyMMdd_HHmmssSSS") + "." +
                FileNameUtil.extName(infile.getOriginalFilename());
        String path = getPath(dto, filename);
        File file = FileUtil.touch(path);
        infile.transferTo(file);
        FileInfo tempFileInfo = new FileInfo();
        tempFileInfo.setStoreId(dto.getStoreId());
        tempFileInfo.setSourceId(dto.getSourceId());
        tempFileInfo.setSourceType(dto.getSourceType());
        tempFileInfo.setName(filename);
        tempFileInfo.setUrl(path);
        tempFileInfo.setType(FileNameUtil.extName(file));
        tempFileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
        tempFileInfo.setUploader(dto.getUploader());
        return fileService.save(tempFileInfo) ? path : "文件保存失败";
    }

    private String getPath(FileInfoDTO dto, String filename) {
        String path;
        if ("storeLog".equals(dto.getFlag())) {
            path = fileUrl + FileUtil.FILE_SEPARATOR + "form" + FileUtil.FILE_SEPARATOR + "storeLog" + FileUtil.FILE_SEPARATOR + dto.getStoreId() + FileUtil.FILE_SEPARATOR + dto.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
        } else {
            path = fileUrl + FileUtil.FILE_SEPARATOR + "form" + FileUtil.FILE_SEPARATOR + dto.getStoreId() + FileUtil.FILE_SEPARATOR + dto.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
        }
        return path;
    }

    @PostMapping("/file/uploadFile")
    @SaCheckPermission(value = "file:upload", orRole = "admin")
    public String uploadFile1(FileInfo fileInfo, @RequestParam(name = "files") MultipartFile[] files) throws IOException {
        for (MultipartFile infile : files) {
            String filename = FileNameUtil.mainName(infile.getOriginalFilename()) + "_" +
                    TimeUtil.format(LocalDateTime.now(), "yyyyMMdd_HHmmssSSS") + "." +
                    FileNameUtil.extName(infile.getOriginalFilename());
            String path = fileUrl + FileUtil.FILE_SEPARATOR + fileInfo.getStoreId() + FileUtil.FILE_SEPARATOR + fileInfo.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
            File file = FileUtil.touch(path);
            infile.transferTo(file);

            FileInfo tempFileInfo = new FileInfo();
            tempFileInfo.setStoreId(fileInfo.getStoreId());
            tempFileInfo.setSourceId(fileInfo.getSourceId());
            tempFileInfo.setSourceType(fileInfo.getSourceType());
            tempFileInfo.setContractId(fileInfo.getContractId());
            tempFileInfo.setName(filename);
            tempFileInfo.setUrl(path);
            tempFileInfo.setType(FileNameUtil.extName(file));
            tempFileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
            tempFileInfo.setUploader(fileInfo.getUploader());
            fileService.save(tempFileInfo);
        }
        return "文件保存成功";
    }

}