【发布时间】:2015-12-23 06:39:00
【问题描述】:
我正在尝试使用“流式”Apache Commons File Upload API 上传一个大文件。
我使用 Apache Commons File Uploader 而不是默认的 Spring Multipart 上传器的原因是当我们上传非常大的文件大小 (~2GB) 时它会失败。我正在开发一个 GIS 应用程序,这种文件上传很常见。
我的文件上传控制器的完整代码如下:
@Controller
public class FileUploadController {
@RequestMapping(value="/upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
// Inform user about invalid request
return;
}
//String filename = request.getParameter("name");
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
try {
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
OutputStream out = new FileOutputStream("incoming.gz");
IOUtils.copy(stream, out);
stream.close();
out.close();
}
}
}catch (FileUploadException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
@RequestMapping(value = "/uploader", method = RequestMethod.GET)
public ModelAndView uploaderPage() {
ModelAndView model = new ModelAndView();
model.setViewName("uploader");
return model;
}
}
问题在于 getItemIterator(request) 总是返回一个没有任何项目的迭代器(即 iter.hasNext() )总是返回 false。
我的application.properties文件如下:
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:19095/authdb
spring.datasource.username=georbis
spring.datasource.password=asdf123
logging.level.org.springframework.web=DEBUG
spring.jpa.hibernate.ddl-auto=update
multipart.maxFileSize: 128000MB
multipart.maxRequestSize: 128000MB
server.port=19091
/uploader 的 JSP 视图如下:
<html>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
File to upload: <input type="file" name="file"><br />
Name: <input type="text" name="name"><br /> <br />
Press here to upload the file!<input type="submit" value="Upload">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</body>
</html>
我可能做错了什么?
【问题讨论】:
-
您是否禁用了 springs 多部分支持,否则您的解决方案将无法正常工作,并且 Spring 已经解析了请求。将所有
multipart属性替换为单个multipart.enabled=false以禁用默认处理。 -
我没有为禁用 spring 多部分支持做任何具体的事情。我尝试在我的
application.properties文件中添加multipart.enabled=false。但是,一旦我这样做了,我每次上传时都会收到405: Request method 'POST' not supported错误。 -
这将表明错误的映射或发布到错误的 url... 启用调试日志记录并查看您发布到哪个 URL 以及您的控制器方法与哪个 URL 匹配。
-
这绝对不是发布到错误 URL 的情况,因为当我删除
multipart.enabled=false时,我的控制器确实被调用(我再次遇到上面帖子中描述的问题)。跨度> -
不,您不想要任何
MultipartResolver,因为它会解析传入的请求并将文件放入内存中。您想自己处理它,因此您不希望其他任何事情弄乱您的多部分请求。
标签: spring spring-boot apache-commons apache-commons-fileupload