使用裸servlet的doPost,当文件上传开始时,会立即调用doPost。然后,我可以使用公共文件FileItemIterator来流式传输请求对象中的文件。
使用Spring MVC,我似乎无法启动控制器方法,直到服务器收到文件后 ,这是不理想的。
我希望我的servlet / controller方法尽可能多地处理文件,并在上传中断时执行一些回滚操作。我目前无法使用Spring MVC做到这一点。
public void doPost(HttpServletRequest request, HttpServletResponse res){
//I can immediately stream the response here
}
VS
@RequestMapping(value="/uploadFiles", method= RequestMethod.POST)
public @ResponseBody String addFiles(ContentManagerTicket ticket, HttpServletRequest request){
//I can't do anything until the files are received - whether i use a HttpServletRequset or MultiPartFile
}
有什么想法吗?谢谢!
答案 0 :(得分:6)
您需要streaming file uploads但是在使用Spring’s multipart (file upload) support时,它会使用the classic approach。这基本上意味着在请求实际传递给控制器之前,会解析请求的所有多部分。这是必需的,因为MultipartFile
可以用作方法参数,为此,它需要可供控制器使用。
如果你想处理流式文件上传,你必须禁用Spring的多部分支持并在控制器中自己the parsing,就像在servlet中一样。
@Controller
public class FileUploadController {
@RequestMapping("/upload")
public void upload(HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
// Inform user about invalid request
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
// Process the input stream
...
}
}
}
}
另请参阅how to upload a file using commons file upload streaming api和Apache commons fileupload "Streaming API"