Spring boot 实现文件的上传下载笔记

Posted -王二毛-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 实现文件的上传下载笔记相关的知识,希望对你有一定的参考价值。

一、实现文件上传

1.1、参考一



二、实现文件上传和下载


package com.qingge.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.common.Constants;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.Files;
import com.qingge.springboot.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/file")
public class FileController 

    @Value("$files.upload.path")
    private String fileUploadPath;

    @Value("$server.ip")
    private String serverIp;

    @Resource
    private FileMapper fileMapper;

    /**
     * 文件上传接口
     * @param file 前端传递过来的文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException 
        String originalFilename = file.getOriginalFilename();//获取文件的原始名称
        String type = FileUtil.extName(originalFilename);//获取文件的类型
        long size = file.getSize();//获取文件大小

        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) //文件目录不存在则创建目录
            parentFile.mkdirs();
        

        String url;
        // 获取文件的md5,通过对比md5避免上传相同的文件
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        
        if (dbFiles != null) //如果有记录,说明本地已经有该文件
            url = dbFiles.getUrl();//,直接获取数据库中的路径即可
         else 
            // 如果没有记录,则上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件,则不删除刚才上传的文件
            url = "http://" + serverIp + ":9090/file/" + fileUUID;
        


        // 存储数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024); // 单位 kb
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);
        
        return url;
    

    /**
     * 文件下载接口   http://localhost:9090/file/fileUUID
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/fileUUID")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException 
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    

    /**
     * 通过文件的md5查询文件
     * @param md5
     * @return
     */
    private Files getFileByMd5(String md5) 
        // 查询文件的md5是否存在
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    

以上是关于Spring boot 实现文件的上传下载笔记的主要内容,如果未能解决你的问题,请参考以下文章

Spring boot 学习笔记 - 整合MyBatis

springboot学习笔记

spring boo的简单搭建(eclipse+springboot + redis + mysql + thymeleaf)

spring-boot实战05:Spring Boo多环境配置及配置属性注入到对象

Spring mvc-文件上传与JSON-学习笔记

Spring mvc-文件上传与JSON-学习笔记