在尝试使用流API实现fileUpload时,我收到如下错误: 当我从the Streaming API网页收集“传统的FileItemFactory被完全忽略”时,我想知道我做错了什么。所以我已经定义了一个基本方法如下:
/**
*
* @param
* @return
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload(); // Create a new file upload handler
// Parse the request
try {
Line 39 --> List items = upload.parseRequest(request); // FileItem
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItemStream item = (FileItemStream) iter.next();
if (!item.isFormField()) {
this.processFITSFile(item);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
但是这会导致以下错误:
SEVERE: Servlet.service() for servlet FitsFileProcessorServlet threw exception
java.lang.NullPointerException: No FileItemFactory has been set.
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:353)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at controller.FITSFileProcessor.doPost(FITSFileProcessor.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:10)
new ServletFileUpload()
创建一个未初始化的实例。它的文件说:
构造一个未初始化的实例 这堂课。一个工厂必须 配置,使用 setFileItemFactory(),之前 试图解析请求。
因此,您需要使用setFileItemFactory()
或使用其他构造函数,它将工厂作为参数。像这样:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
更多信息,请参阅the documentation。这个例子也来自那里。
或者,你可以使用streaming API,但是你需要以不同的方式获得迭代器:
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
...
}