- Controller的接收有2种方式,原理都是 org.springframework.web.multipart.support.StandardMultipartHttpServletRequest
@PostMapping(value = "/testMultipartFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String testMultipartFile(@RequestParam(value = "file[]", required = true) List<MultipartFile> multipartFile) {
String fileName = multipartFile.get(0).getOriginalFilename();
String pathname = TMP + fileName;
try {
multipartFile.get(0).transferTo(new File(pathname));
} catch (Exception e) {
log.error("testMultipartFile exception!", e);
}
return fileName;
}
@PostMapping(value = "/upload")
public String upload(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest =
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
multipartRequest.getFileNames().forEachRemaining(t->log.info(t));
List<MultipartFile> multipartFiles = multipartRequest.getFiles("file[]");
MultipartFile[] multipartFile = multipartFiles.toArray(new MultipartFile[0]);
String fileName = multipartFile[0].getOriginalFilename();
String pathname = TMP + fileName;
return pathname;
}
- application.yml
spring.servlet.multipart: max-file-size: 10MB # 文件的最大大小 max-request-size: 50MB # 请求的最大大小 file-size-threshold: 0 # 文件大小阈值,当大于这个阈值时将写入到磁盘,否则在内存中。 默认值为0
SpringBoot提供了自动装配类org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,装配属性见 MultipartProperties
前端使用 Content-Type = "multipart/form-data" + POST 方式发起请求。应该就能得到正确结果了。
- nginx 方面
需要设置文件保存的有读写权限目录,并必要的内存调整。
error_log /data/logs/error/nginx_error.log info; # 配置异常日志文件
http
{
sendfile on; # 开启高效文件传输模式
client_max_body_size 100m; # 默认 1M,表示客户端请求服务器最大允许大小。 如果请求的正文数据大于client_max_body_size,HTTP协议会报错 413 Request Entity Too Large。
client_body_buffer_size 2m; # Nginx分配给请求数据的Buffer大小。如果请求的数据小于client_body_buffer_size直接将数据先在内存中存储,如果请求的值大于client_body_buffer_size小于client_max_body_size,就会将数据先存储到临时文件中。
client_body_temp_path /data/temp_file; # 文件临时目录 需要有可读写权限
log_format access '----$remote_addr - [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_real_ip [$upstream_addr]';
access_log /usr/local/nginx/log/access.log access; # 请求日志
#Limit
limit_req_zone $binary_remote_addr zone=xxx:10m rate=5r/s; # 限流
}
否则报错
- 其次 在java代码端,有些影性的代码会导致导致MultipartFile解析为空。 如下文
@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
dispatcherServlet.setPublishEvents(false);
ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
return registration;
}