@RequestMapping(value = "/save", method = RequestMethod.POST)
public ResponseResult saveSharecare(HttpServletRequest request, @RequestPart(value = "file") MultipartFile[] multipartFiles,@Valid ShareCareDto shareCareDto){}
解释:
1): request不多说了,默认获取所有的,可以写,也可以不写,也可以注解加httpheader cookie等等,按你所需
2):上传文件一定要加@RequestPart(value="file"),如果是多个文件(这里就是多个),value="file",表示name值就是file,多个文件name值要相等。 如果不加@RequestPart注解,httpServletRequest仍然可以获取多个multipartFiles,但是这个方法入参multipartFiles就没值,所以要加上该注解
3):sharecareDto就是你传输的DTO实体,这里只是个例子@Valid注解是开启验证,这个实体的属性哪些必填,哪些字段大小等等的注解验证。
以上就是所有配置。
问题:1:为什么这样配置就可以上传? spring.io官网给出了答案,见 https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-multipart-file-upload-configuration
注: MultipartAutoConfiguration 类增加了StandardServletMultipartResolver 对Servlet 3 javax.servlet.http.Part进行了增强,所以无需配置了。
客户端http完整请求示例:
POST /v1/sharecare/save HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
content-type: multipart/form-data; boundary=---------------------------22751826015688
origin: moz-extension://7450cf37-12f8-4d6e-af59-921a7f04d962
Content-Length: 426396
token: 123456
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
-----------------------------22751826015688
Content-Disposition: form-data; name="headline"
123456
-----------------------------22751826015688
Content-Disposition: form-data; name="file"; filename="IMG_0461.jpg"
Content-Type: image/jpeg
���
-----------------------------22751826015688
Content-Disposition: form-data; name="file"; filename="IMG_0462.jpg"
Content-Type: image/jpeg
���
-----------------------------22751826015688
完!