MultipartFile 对上传的文件大小进行限制

@Slf4j
@Component
public class MultipartFileUtil {

private final static Integer FILE_SIZE = 5;//文件上传限制大小
private final static String FILE_UNIT = "M";//文件上传限制单位(B,K,M,G)

    /**
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位(B,K,M,G)
     * @描述 判断文件大小
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equalsIgnoreCase(unit)) {
            fileSize = (double) len;
        } else if ("K".equalsIgnoreCase(unit)) {
            fileSize = (double) len / 1024;
        } else if ("M".equalsIgnoreCase(unit)) {
            fileSize = (double) len / 1048576;
        } else if ("G".equalsIgnoreCase(unit)) {
            fileSize = (double) len / 1073741824;
        }
        return !(fileSize > size);
    }

    //文件上传调用
    public static String upload(MultipartFile file) {
        boolean flag = checkFileSize(file.getSize(), FILE_SIZE, FILE_UNIT);
        if (!flag) {
            throw new RuntimeException("上传文件大小超出限制");
        }
    }

}
PS:以上基础需要项目本身设定好最大文件阈值,在阈值的基础上进行限制大小提示,如果不设置,文件上传大小默认1MB,超出则抛异常

#设置单个文件最大请求100MB,最多一次请求2个文件(具体设定看自己需求)
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=200MB

#设置文件上传大小不进行限制
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1

/**
     * @描述 文件下载
     * @参数 [response, filePath, filename]
     * @返回值 javax.servlet.http.HttpServletResponse
     * @创建时间 2021/6/29
     */
    public static void download(HttpServletResponse response, String filePath, String filename) {
        try {
            // path是指欲下载的文件的路径
            File file = new File(filePath);
            // 以流的形式下载文件
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

你可能感兴趣的:(MultipartFile 对上传的文件大小进行限制)