上傳多個檔案
要接收通過單個 HTTP Post 上傳的多個檔案,你需要執行以下操作:
@RequestMapping(
value = "...",
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
)
public Object uploadFile(
@RequestPart MultipartFile[] files
) {
for (file : files) {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
String contentType = file.getContentType();
.
.
.
}
}
請注意,@RequestPart
引數的名稱需要與請求中的部件名稱匹配。
作為 HTML:
<form action="/..." enctype="multipart/form-data" method="post">
<input type="file" name="files">
<input type="file" name="files">
</form>
作為原始 HTTP 請求:
POST /... HTTP/1.1
Host: ...
Content-Type: multipart/form-data; boundary=----------287032381131322
------------287032381131322
Content-Disposition: form-data; name="files"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
------------287032381131322
Content-Disposition: form-data; name="files"; filename="banana.jpeg"
Content-Type: image/jpeg
GIF87a.............,...........D..;
------------287032381131322--
該請求意味著以下內容:
files[0].getOriginalFilename() == "r.gif"
files[0].getContentType() == "image/gif"
files[1].getOriginalFilename() == "r.jpeg"
files[1].getContentType() == "image/jpeg"