java 文件上传

该代码示例展示了如何使用Spring Boot实现文件上传、存储、删除和复制操作。通过`CommonFileInfoController`,文件被接收并保存到指定路径,同时在数据库中创建对应记录。`UploadUtils`类提供了文件操作的辅助方法,包括上传、删除、复制路径及管理目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

@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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值