美文网首页
Spring Boot支持文件上传

Spring Boot支持文件上传

作者: 十毛tenmao | 来源:发表于2019-04-28 22:20 被阅读0次

    现在的Java Web项目一般都是Json API,为前端提供数据接口,但是有时候后台也需要提供一些文件导入的功能,需要支持文件上传。在Spring Boot中实现起来非常简单,不需要引入额外的依赖和配置(默认配置就可以了)

    添加依赖pom.xml

    其实都是Spring Web的依赖,没有特殊依赖项

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1-jre</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    

    SpringBootApplication

    @Slf4j
    @RestController
    @SpringBootApplication
    public class UploadApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UploadApplication.class, args);
        }
    
        @PostMapping("upload")
        public String upload(@RequestParam("file") MultipartFile file) {
            try {
                String s = CharStreams.toString(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
            } catch (IOException e) {
                log.warn("fail to read file", file.getOriginalFilename(), e);
                return e.getMessage();
            }
            return "success";
        }
    }
    

    文件上传的配置项

    # The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited.
    # 上传的文件的大小限制
    spring.servlet.multipart.max-file-size=1KB
    # The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.
    # multipart/form-data请求的大小限制
    spring.servlet.multipart.max-request-size=128KB
    
    

    文件上传

    • 上传小于1KB的文件


      文件上传
    • 上传大于1KB的文件(超过配置的最大文件大小)

    {
        "timestamp": "2019-04-28T12:39:26.437+0000",
        "status": 500,
        "error": "Internal Server Error",
        "message": "Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1024 bytes.",
        "path": "/upload"
    }
    

    参考

    相关文章

      网友评论

          本文标题:Spring Boot支持文件上传

          本文链接:https://www.haomeiwen.com/subject/wsxsnqtx.html