欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot文件上传

程序员文章站 2022-05-04 09:56:41
...

如何上传

Controller

@RequestMapping(value = "upload/image", method = RequestMethod.POST)
public ResponseVO uploadImage(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
	FileUtil.saveFile("/local/image/", name, file.getBytes());
}

FileUtil工具类

package com.dongbawen.common.util;

import com.alibaba.fastjson.util.IOUtils;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtil {

    private static final int BUFFER = 1024 * 8;

    /**
     * 允许下载的文件类型,根据需求自己添加(小写)
     */
    public static final String[] VALID_FILE_TYPE = {"xlsx", "zip"};

    /**
     * 压缩文件或目录
     *
     * @param fromPath 待压缩文件或路径
     * @param toPath   压缩文件,如 xx.zip
     */
    public static void compress(String fromPath, String toPath) throws IOException {
        File fromFile = new File(fromPath);
        File toFile = new File(toPath);
        if (!fromFile.exists()) {
            throw new FileNotFoundException(fromPath + "不存在!");
        }
        try (
                FileOutputStream outputStream = new FileOutputStream(toFile);
                CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
                ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)
        ) {
            String baseDir = "";
            compress(fromFile, zipOutputStream, baseDir);
        }
    }

    /**
     * 文件下载
     *
     * @param filePath 待下载文件路径
     * @param fileName 下载文件名称
     * @param delete   下载后是否删除源文件
     * @param response HttpServletResponse
     * @throws Exception Exception
     */
    public static void download(String filePath, String fileName, Boolean delete, HttpServletResponse response) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("文件未找到");
        }

        String fileType = getFileType(file);
        if (!fileTypeIsValid(fileType)) {
            throw new Exception("暂不支持该类型文件下载");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } finally {
            if (delete) {
                delete(filePath);
            }
        }
    }

    /**
     * 递归删除文件或目录
     *
     * @param filePath 文件或目录
     */
    public static void delete(String filePath) {
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                Arrays.stream(files).forEach(f -> delete(f.getPath()));
            }
        }
        try {
            Files.delete(Paths.get(filePath));
        } catch (IOException e) {
            log.error("删除失败", e);
        }
    }

    /**
     * 获取文件类型
     *
     * @param file 文件
     * @return 文件类型
     * @throws Exception Exception
     */
    private static String getFileType(File file) throws Exception {
        Preconditions.checkNotNull(file);
        if (file.isDirectory()) {
            throw new Exception("file不是文件");
        }
        String fileName = file.getName();
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    /**
     * 校验文件类型是否是允许下载的类型
     * (出于安全考虑:https://github.com/wuyouzhuguli/FEBS-Shiro/issues/40)
     *
     * @param fileType fileType
     * @return Boolean
     */
    private static Boolean fileTypeIsValid(String fileType) {
        Preconditions.checkNotNull(fileType);
        fileType = StringUtils.lowerCase(fileType);
        return ArrayUtils.contains(VALID_FILE_TYPE, fileType);
    }

    private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
        if (file.isDirectory()) {
            compressDirectory(file, zipOut, baseDir);
        } else {
            compressFile(file, zipOut, baseDir);
        }
    }

    private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {
        File[] files = dir.listFiles();
        if (files != null && ArrayUtils.isNotEmpty(files)) {
            for (File file : files) {
                compress(file, zipOut, baseDir + dir.getName() + "/");
            }
        }
    }

    private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
        if (!file.exists()) {
            return;
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zipOut.putNextEntry(entry);
            int count;
            byte[] data = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                zipOut.write(data, 0, count);
            }
        }
    }

    public static String saveFile(String path,String fileName, byte[] bytes) throws Exception {
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            String filePath = path + fileName;
            fileOutputStream = new FileOutputStream(new File(filePath));
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            bufferedOutputStream.write(bytes);
            return fileName;
        } finally {
            IOUtils.close(bufferedOutputStream);
            IOUtils.close(fileOutputStream);
        }
    }
}

由于FileUtil依赖fastjson,所以需要在pom中引入这个jar

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.31</version>
</dependency>

这样就可以把文件上传到指定的目录了,上文中的上传路径为/local/image/,这个表示你项目所在磁盘的根目录。
Spring Boot文件上传

如何访问

如果是上传到项目目录下访问倒是比较好访问,但是上传到项目目录下每次部署项目的时候为免太麻烦了,如果像问中这种上传到某个与项目无关的目录(比如E盘根目录下)那么怎么访问呢?需要做如下配置

spring:
	resources:
    #资源存放的磁盘位置
    static-locations: classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resource,file:E://local//image/

这个意思代表,当我们查找静态资源的时候,依次按照上诉路径去查找,知道找到为止。
关于springboot的静态资源加载顺序可以参考这篇文章
Spring Boot文件上传

报错

这样设置当上传图片或者文件大于1MB的时候会报错

The field file exceeds its maximum permitted size of 1048576 bytes.

这是因为Spring Boot规定,每个文件的配置最大为1Mb,单次请求的文件的总数不能大于10Mb。要更改这个默认值需要在配置文件(如application.properties)中加入两个配置
Spring Boot2.0之后的版本配置为:

spring.servlet.multipart.max-file-size = 10MB  
spring.servlet.multipart.max-request-size=100MB

要不限制设置成-1,如下

spring:
	servlet:
	    multipart:
	      max-file-size: -1
	      max-request-size: -1
相关标签: springboot文件上传