springboot(三)文件上传,异常处理

39 阅读1分钟

静态资源访问

资源存放路径

image.png

资源访问url

image.png

文件上传

前端html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <div>
        <input type="file"
               id="file"
               name="file"
               value="选择图片"
               accept="image/jpeg,image/jpg,image/png">
    </div>
    <div>
        <input type="submit" value="上传文件"/>
    </div>
</form>
</body>
</html>

后端

增加上传路径(把propa修改为yml)

image.png

web:
  upload-path: F:/test/java/springboot2/src/main/resources/upload/

获取配置的上传路径

package com.example.springboot2.controller;

import org.springframework.beans.factory.annotation.Value;

public class UploadFileController {

    @Value("${web.upload-path}")
    private String uploadPath;

}

上传

package com.example.springboot2.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;



@RestController
public class UploadFileController {

    @Value("${web.upload-path}")
    private String uploadPath;

    @PostMapping("upload")
    public String upload(MultipartFile file) throws Exception {
        file.transferTo(new File(uploadPath + file.getOriginalFilename()));
        return "上传成功";
    }
}

异常处理

springboot默认文件大小的限制是1MB,超过1MB会出现这个错误

image.png

image.png

文件大小限制异常处理

@ControllerAdvice: 捕获异常

package com.example.springboot2.exception;

import com.example.springboot2.util.JSONResult;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GraceExceptionHandler {

    @ExceptionHandler(FileSizeLimitExceededException.class)
    @ResponseBody
    public JSONResult returnMaxFileSizeLimit(FileSizeLimitExceededException e){
        return new JSONResult(400,"文件大小不能超过100KB","{}");
    }
}

image.png

配置文件上传大小限制

application.yml

spring:  
servlet:  
multipart:  
max-file-size: 100000KB # 文件上传大小的限制,设置最大值,不能超过,否则报错  
max-request-size: 2MB # 文件最大请求限制,用于批量