springboot上传-下载文件-Hutool

  • Post author:
  • Post category:其他




springboot上传-下载文件-Hutool



1.导入依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.18</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>



2.数据库表结构

CREATE TABLE `sys_file` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `size` bigint DEFAULT NULL,
  `url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `is_delete` tinyint DEFAULT '0',
  `enable` tinyint(1) DEFAULT '1',
  `md5` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;



3.实体类Files

@Data
@TableName("sys_file")
public class Files {
    @TableId(type = IdType.AUTO)
    private Integer id; //主键
    private String name;//文件名
    private String type;//类型
    private Long size;//大小
    private String url;//路径
    private String md5; //确认文件唯一
    private Boolean isDelete; //是否删除
    private Boolean enable; //是否可用
}



4.fileMapper (mybatis-plus)

public interface FileMapper extends BaseMapper<Files> {
}

上传路径

files:
  upload:
    path: E:/项目/files/



5.controller

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.filedemo.entity.Files;
import com.example.filedemo.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Value;
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;

    @Resource
    private FileMapper fileMapper;
	//上传
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //文件名.jpg
        String type = FileUtil.extName(originalFilename);//.jpg
        long size = file.getSize();//大小

        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type; //41b1076684904f9cb4a503fb028db94b.jpg
        File uploadFile = new File(fileUploadPath + fileUUID);
        //先存储到磁盘
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        String url;
        file.transferTo(uploadFile);
            //获取文件的md5
            //使用m5 避免重复上传相同的文件
          String  md5 = SecureUtil.md5(uploadFile);
            Files dbFiles = getFileByMD5(md5);
            if (dbFiles != null) {
                url = dbFiles.getUrl();
                uploadFile.delete();
            } else {
                url = "http://localhost:9090/file/" + fileUUID;
            }
            //保存到数据库
            Files saveFile = new Files();
            saveFile.setName(originalFilename);
            saveFile.setType(type);
            saveFile.setSize(size / 1024);
            saveFile.setUrl(url);
            saveFile.setMd5(md5);
            fileMapper.insert(saveFile);
            return url;

    }
	
    //下载
    @GetMapping("/{fileUUID}")
    public void dowmload(@PathVariable String fileUUID,
                         HttpServletResponse response) throws IOException {

        File uploadFile = new File(fileUploadPath + fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Contene-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
    public Files getFileByMD5(String md5){
        QueryWrapper<Files> wrapper = new QueryWrapper<>();
        wrapper.eq("md5",md5);
        List<Files> filesList = fileMapper.selectList(wrapper);
        return filesList.size()==0? null: filesList.get(0);
    }
}



版权声明:本文为xixihaha_coder原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。