赞
踩
springBoot使用CommonsMultipartFile工具上传文件遇到报错
原文:https://blog.csdn.net/Dawn____Dawn/article/details/104009433
旧的springMVC项目中使用CommonsMultipartFile类型来接收上传的文件,现在进行迁移,框架使用springboot2.0+ ,始终无法接收请求。
Multipart配置类:
- package com.example.hellospringboot.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
- @Configuration
- public class MultipartConfig {
- @Bean(name = "multipartResolver")
- public CommonsMultipartResolver getCommonsMultipartResolver() {
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
- multipartResolver.setMaxUploadSize(20971520);
- multipartResolver.setMaxInMemorySize(1048576);
- return multipartResolver;
- }
- }
关闭Spring Boot的Multipart自动配置,否则通过CommonsMultipartFile依然无法接收到文件。@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
- package com.example.hellospringboot;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
- import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
- @EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
- @Configuration
- @ComponentScan
- @EnableSwagger2
- public class HellospringbootApplication {
- public static void main(String[] args) {
- SpringApplication.run(HellospringbootApplication.class, args);
- }
- }
-
maven配置(文件上传相关依赖):
- <!--文件上传:commons-fileupload中包含了commons-io-->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.4</version>
- </dependency>
在页面上上传文件并在本地对应位置能找到上传的文件即配置成功。
- package com.example.hellospringboot.controller;
-
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- 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("/test")
- @Api(value = "前端控制器")
- public class TestController {
-
- @RequestMapping(value = "/upload", method = RequestMethod.POST)
- @ApiOperation(value = "文件上传", notes = "文件上传")
- public String upload(@RequestParam(value="file", required = false) MultipartFile file){
- //该路径写死了,需要修改
- File file2 = new File("F:\\a.txt");
- try {
- file.transferTo(file2);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "";
- }
- }
项目目录:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。