0
点赞
收藏
分享

微信扫一扫

java 文件上传

敬亭阁主 2022-03-17 阅读 41
package com.zeshang.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dto.FileDto;
import com.entity.CommonFileInfoEntity;
import com.service.CommonFileInfoService;
import com.util.UploadUtils;
import io.common.utils.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


/**
* 文件信息
*
* @author Bellth bellthking@163.com
* @since 3.0 2021-10-24
*/
@RestController
@RequestMapping("file/commonfileinfo")
public class CommonFileInfoController {
    @Autowired
    private CommonFileInfoService commonFileInfoService;

    @PostMapping("upload")
    @Transactional(rollbackFor = Exception.class)
    public Result<FileDto> uploadApproveFile(@RequestParam("file") MultipartFile file, String fileType) throws Exception {
        if (file.isEmpty()) {
            return new Result().error("文件不能为空");
        }
        String fileName = FilenameUtils.getName(file.getOriginalFilename());
        String newName = IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(46));
        // 上传文件
        String filePath = UploadUtils.uploadFile(newName, file.getBytes());
        // 添加表记录
        CommonFileInfoEntity entity = new CommonFileInfoEntity(){{
            setFileName(fileName);
            setFilePath(filePath + File.separator + newName);
            setFileType(fileType);
        }};
        commonFileInfoService.save(entity);
        return new Result<FileDto>().ok(new FileDto(){{
            String filePath = entity.getFilePath();
            int i = -1;
            if (!"/".equals(File.separator)) {
                while ((i = filePath.indexOf(File.separator)) > -1) {
                    filePath = filePath.substring(0, i) + "/" + filePath.substring(i + 1);
                }
            }
            setFilePath(filePath);
            setFileName(fileName);
            setId(entity.getId());
            setFileType(fileType);
        }});
    }
}
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

public class UploadUtils {

    public static final String UPLOAD_PATH = getUploadPath();

    private static String getUploadPath() {
        try {
            String serverPath = ResourceUtils.getURL("classpath:").getPath();
            String uploadPath =  new File(serverPath).getParentFile().getParentFile().getParent() + File.separator + "upload" + File.separator;
            uploadPath = uploadPath.startsWith("file:") ? uploadPath.replace("file:", "") : uploadPath;
            return uploadPath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void deleteFile(String filePath) {
        try {
            Files.deleteIfExists(Paths.get(UPLOAD_PATH + filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deletePath(String path) {
        try {
            Path dir = Paths.get(UPLOAD_PATH + path);
            DeleteDirectory deleteDirectory = new DeleteDirectory();
            EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            Files.walkFileTree(dir, opts, Integer.MAX_VALUE, deleteDirectory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyFileTo(String sourceFile, String targetFile, String targetPath) {
        try {
            Path sourcePath = Paths.get(UPLOAD_PATH + sourceFile);
            Path targetFilePath = Paths.get(UPLOAD_PATH + targetFile);
            Path tPath = Paths.get(UPLOAD_PATH + targetPath);
            if (Files.notExists(tPath)) {
                Files.createDirectories(tPath);
            }
            if (!Files.exists(targetFilePath)) {
                Files.createFile(targetFilePath);
            }
            Files.copy(sourcePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String uploadFile(String fileName, byte[] bytes) {
        String filePath = IdWorker.getIdStr();
        File path = new File(UPLOAD_PATH + filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
        try {
            Files.write(Paths.get(UPLOAD_PATH + filePath + File.separator + fileName), bytes, StandardOpenOption.CREATE);
            return filePath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    static class DeleteDirectory implements FileVisitor {

        boolean deleteFileByFile(Path file) throws IOException {
            return Files.deleteIfExists(file);
        }

        @Override
        public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
            boolean success = deleteFileByFile((Path) file);

            if (success) {
                System.out.println("Deleted: " + (Path) file);
            } else {
                System.out.println("Not deleted: " + (Path) file);
            }

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
            if (exc == null) {
                System.out.println("Visited: " + (Path) dir);
                boolean success = deleteFileByFile((Path) dir);

                if (success) {
                    System.out.println("Deleted: " + (Path) dir);
                } else {
                    System.out.println("Not deleted: " + (Path) dir);
                }
            } else {
                exc.printStackTrace();
            }
            return FileVisitResult.CONTINUE;
        }
    }
}

举报

相关推荐

0 条评论