我需要一次上传多个文件并保存在服务器中。但是ServletFileUpload #parseRequest(request)方法缺少请求中的第一个文件,即第0个索引文件,并从索引1返回文件列表,依此类推。
请求:
请求标题:
POST /restcon/fileUploadTest HTTP/1.1
Host: localhost:8089
Connection: keep-alive
Content-Length: 1371330
Pragma: no-cache
Cache-Control: no-cache
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryd9n7NKPBSR9245hd
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,te;q=0.6
请求有效负载:
------WebKitFormBoundaryd9n7NKPBSR9245hd
Content-Disposition: form-data; name="fileUpload"; filename="Hydrangeas.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryd9n7NKPBSR9245hd
Content-Disposition: form-data; name="fileUpload1"; filename="Jellyfish.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryd9n7NKPBSR9245hd--
Java代码:
//为基于磁盘的文件项创建工厂 DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
File repository = new File(System.getProperty("java.io.tmpdir"));
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> files = upload.parseRequest(req);
System.out.println("files size : "+files.size());
for(FileItem file : files) {
String name = file.getName();
System.out.println("file name : "+ name);
}
} catch (FileUploadException e) {
}
返回的List包含Jellyfish.jpg(第二个文件)并且不包含Hydrangeas.jpg(第一个文件)。