Learn Springboot & Vue 4 Spring boot文件上传

77 阅读2分钟

Upload Files

properties中先写一个uploadPath:

files.upload.path=E:/SpringVueWeb/springWeb/files/

FileController中使用该变量

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

之后就是先保存到本地磁盘,然后再保存到数据库:

package com.example.springweb.contoller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
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;
import java.io.IOException;

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

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


    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        String type = FileUtil.extName(originalFileName);
        long size = file.getSize();

        // 先存储到磁盘
        File uploadParentFile = new File(fileUploadPath);
        // 判断配置的文件目录是否存在,若不存在则创建一个新目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + type);
        // 把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);
        // 存储数据库

        return "";
    }
}

在拦截器中先将file的接口全都exclude掉,否则会因无token而报错

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(jwtInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/user/login", "/user/register", "/**/import", "/**/export", "/file/**"); // 拦截所有请求,通过判断token是否合法来决定是否需要登录
}

测试一下接口

image.png

image.png

成功在本地得到该文件

之后就是要将该文件保存到数据库中

所以我们需要新建一个数据库捏

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

然后新建文件类

package com.example.springweb.entity;


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@TableName("sys_file")
@AllArgsConstructor
@NoArgsConstructor
public class Files {

    @TableId(type = IdType.AUTO)
    private Integer id;

    @TableField("name")
    private String name;

    @TableField("type")
    private String type;

    @TableField("size")
    private Long size;

    @TableField("url")
    private String url;

    @TableField("is_delete")
    private Boolean isDelete;

    @TableField("enable")
    private Boolean enable;
}

之后使用fileService将该文件直接insert

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

@Resource
private FileMapper fileMapper;


/**
 * 文件上传接口
 * @param file
 * @return
 */
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IOException {
    String originalFileName = file.getOriginalFilename();
    String type = FileUtil.extName(originalFileName);
    long size = file.getSize();

    // 先存储到磁盘
    File uploadParentFile = new File(fileUploadPath);
    // 判断配置的文件目录是否存在,若不存在则创建一个新目录
    if (!uploadParentFile.exists()) {
        uploadParentFile.mkdirs();
    }
    // 定义一个文件唯一的标识码
    String uuid = IdUtil.fastSimpleUUID();
    String fileUUID = uuid + StrUtil.DOT + type;
    File uploadFile = new File(fileUploadPath + fileUUID);

    // 把获取到的文件存储到磁盘目录
    file.transferTo(uploadFile);

    String url = "http://localhost:9090/" + fileUUID;
    // 存储数据库
    Files saveFile = new Files();
    saveFile.setName(originalFileName);
    saveFile.setType(type);
    saveFile.setSize(size);
    saveFile.setUrl(url);
    fileMapper.insert(saveFile);
    return url;
}

download File

根据上面的POST接口,可以直接写一个download接口

    /**
     * 文件下载接口http://localhost:9090/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    private 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();
    }
}

..其实不怎么能用到File相关,摆烂