如何设置Apache File Upload-FileItemFactory?

时间:2018-11-25 00:43:40

标签: java

我很想使用upload library来做

        List<FileItem> fileItems = FileUpload.parse(bytes, contentType);
        for(FileItem item : fileItems) {
            if(item.isFormField()) {

            } else {
                content = item.getInputStream();
            }
        }

这引发的问题:

java.lang.NullPointerException: No FileItemFactory has been set.
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:337)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
    at delight.fileupload.FileUpload.parse(FileUpload.java:20)

查看代码的根本原因是

    FileItemFactory fac = getFileItemFactory();
    if (fac == null) {
        throw new NullPointerException("No FileItemFactory has been set.");
    }

显然,整个文件上传代码为:

public class FileUpload {
  public static List<FileItem> parse(final byte[] data, final String contentType) {
    try {
      final ServletFileUpload upload = new ServletFileUpload();
      final HttpServletRequest request = new MockHttpServletRequest(data, contentType);
      final boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      if ((!isMultipart)) {
        throw new Exception("Illegal request for uploading files. Multipart request expected.");
      }
      final List<FileItem> iter = upload.parseRequest(request);
      return iter;
    } catch (Throwable _e) {
      throw Exceptions.sneakyThrow(_e);
    }
  }
}

此代码中可以做什么来解决引发的异常?给定上面的代码,如何正确设置File项目工厂?

0 个答案:

没有答案