JAVA后台文件上传接口实现(“.doc“, “.docx“, “.xls“, “.xlsx“, “.pdf“, “.jpg“, “.png“, “.mp4“)

实现文件上传主要依赖Spring的MultipartFile类,MultipartFile是SpringMVC提供简化上传操作的工具类。
  在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
1.Controller.class

/**
 * Created on 2024/3/25.
 */
@RestController
@RequestMapping("/Upload")
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    private final String[] sufix = {".doc", ".docx", ".xls", ".xlsx", ".pdf", ".jpg", ".png", ".mp4"};
    @Autowired
    UploadRepository uploadRepository;
    @Value("${local-path}")
    private String localPath;

    // 文件上传、编辑
    @PostMapping("/upload")
    public ResponseObject uploadFile(HttpServletRequest request, @RequestParam MultipartFile files, UploadFile uploadFile) {
        String id = null;
        if(uploadFile.getId() == null){
            id = UUID.randomUUID().toString();
        } else {
            id = uploadFile.getId();
        }

        String year = DateUtil.getCurrentYear();
        FileOutputStream out = null;
        try {
            String fileName = files.getOriginalFilename();
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 文件保存路径
            String type = "file";
            String filePath = "";
            uploadFile.setRealName(fileName);
            uploadFile.setId(id);
            uploadFile.setFileName(id + "." + suffix);
            uploadFile.setSuffix(suffix);
            uploadFile.setStatus("0");
            uploadFile.setFileType(FileTypeUtil.getType(suffix).toString());
            uploadFile.setUpDate(DateUtil.getDateTime());
            // uploadFile.setCreateUserId(user.getUserId());
            uploadFile.setCreateTime(DateUtil.getDateTime());
            String relatPath = "";
            if (uploadFile.getFolderName() != null) {
                relatPath = "files/upload/" + year + "/" + type + "/" + uploadFile.getFolderName() + "/";
            } else {
                relatPath = "files/upload/" + year + "/" + type + "/";
            }
            filePath = localPath + relatPath + uploadFile.getFileName();
            uploadFile.setPath(filePath);
            File dest = new File(localPath + relatPath + uploadFile.getFileName());
            uploadFile.setRelatPath(relatPath);
            // 获取文件存放地址
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件保存到指定目录下
            files.transferTo(dest);

            // 文件信息保存到数据库
            uploadRepository.save(uploadFile);

            Map<String, Object> map = new HashMap<>();
            map.put("id", uploadFile.getId());
            map.put("fileType", uploadFile.getFileType());
            map.put("realName", uploadFile.getRealName());
            map.put("path", uploadFile.getRelatPath() + uploadFile.getFileName());
            return ResponseObject.ok("上传成功", map);
        } catch (Exception e) {
            return ResponseObject.error("上传失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 文件查询
    @PostMapping("/getFileById")
    public ResponseObject getFileById(@RequestBody UploadFile uploadFile) {
        Optional<UploadFile> file = uploadRepository.findById(uploadFile.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", file.get().getId());
        map.put("fileType", file.get().getFileType());
        map.put("realName", file.get().getRealName());
        map.put("path", file.get().getRelatPath() + file.get().getFileName());
        return ResponseObject.ok("文件查询成功", map);
    }

    // 文件删除
    @PostMapping("/delFileById")
    public ResponseObject delFileById(@RequestBody UploadFile uploadFile) {
        Optional<UploadFile> upload = uploadRepository.findById(uploadFile.getId());
        if(upload.isPresent()){
            File file = new File(upload.get().getPath());
            file.delete();
            uploadRepository.deleteById(uploadFile.getId());
            return ResponseObject.ok("文件删除成功!");
        } else {
            return ResponseObject.ok("文件未找到!");
        }
    }

}

2.application.yml
添加文件保存的绝对路径:

# 文件上传路径
localPath: "D:/file/"

3.WebMvcConfig.class
添加文件路径配置,可以访问到文件:

/**
 * Created on 2023/2/27.
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Value("${localPath}")
    private String localPath;
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry handlerRegistry) {
        handlerRegistry.addResourceHandler("/static/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
        handlerRegistry.addResourceHandler("/files/**").addResourceLocations("file:"+localPath+"files\\");

        super.addResourceHandlers(handlerRegistry);

       handlerRegistry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);

        super.addResourceHandlers(handlerRegistry);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王八八。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值