如何在嵌入式Jetty中实现FileUpload?

Tho*_*Kay 3 file-upload embedded-jetty

我正在写一个包含网络服务器的Android应用程序.因此我使用Embedded Jetty(8.0.1).

我想要做的下一步是实现文件上传.

HTML看起来像这样,我认为正确:

<form action=\"fileupload\" method=\"post\" enctype=\"multipart/form-data\"> 
    <table>
        <tbody>
            <tr>
                <td><input type=\"file\" name=\"userfile1\" /></td>
            </tr>
            <tr>
                <td>
                     <input type=\"submit\" value=\"Submit\" /><input type=\"reset\" value=\"Reset\" />
                </td>
            </tr>
        </tbody>
    </table>
</form>
Run Code Online (Sandbox Code Playgroud)

当我使用这个表单时,我可以在logcat中看到我收到了一个文件但是我无法在我的Servlet中访问这个文件.

我试过了

File file1 = (File) request.getAttribute( "userfile1" );
Run Code Online (Sandbox Code Playgroud)

并具有以下功能:

request.getParameter()
Run Code Online (Sandbox Code Playgroud)

但每次我收到一个NULL对象.我该怎么办?

And*_*rew 10

由于这是一个多部分请求,而您正在上传"文件"部分,因此您需要使用以获取数据

request.getPart("userfile1");
Run Code Online (Sandbox Code Playgroud)

对于请求中不属于"file"类型的元素,例如input type ="text",则可以通过以下方式访问这些属性request.getParameter.

需要注意的是,Jetty 8.0.1已经很老了,最新的Jetty版本(截至编写时,8.1.12)包含了一些重要的错误修正来进行多部分处理.

如果你升级你的Jetty版本,你可能必须明确启用Multipart处理,因为Jetty更严格地执行Servlet 3.0规范(https://bugs.eclipse.org/bugs/show_bug.cgi?id=395000),使用@MultipartConfig如果使用servlet,则为注释.

使用处理程序,您必须Request.__MULTIPART_CONFIG_ELEMENT在调用之前手动将一个属性作为属性添加到您的请求中getPart(s)

if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
  baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
}
Run Code Online (Sandbox Code Playgroud)

这将允许您解析多部分请求,但如果以这种方式注入配置,则不会清除创建的临时多部分文件.对于servlet,它由附加到Request的ServletRequestListener处理(请参阅org.eclipse.jetty.server.Request#MultiPartCleanerListener).

因此,我们所做的是在我们的处理程序链的早期有一个HandlerWrapper,它根据需要添加了多部分配置,并确保在请求完成后清理多部分文件.例:

import java.io.IOException;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiPartInputStreamParser;

/**
 * Handler that adds the multipart config to the request that passes through if
 * it is a multipart request.
 *
 * <p>
 * Jetty will only clean up the temp files generated by
 * {@link MultiPartInputStreamParser} in a servlet event callback when the
 * request is about to die but won't invoke it for a non-servlet (webapp)
 * handled request.
 *
 * <p>
 * MultipartConfigInjectionHandler ensures that the parts are deleted after the
 * {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)}
 * method is called.
 *
 * <p>
 * Ensure that no other handlers sit above this handler which may wish to do
 * something with the multipart parts, as the saved parts will be deleted on the return
 * from
 * {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)}.
 */
public class MultipartConfigInjectionHandler extends HandlerWrapper {
  public static final String MULTIPART_FORMDATA_TYPE = "multipart/form-data";

  private static final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement(
      System.getProperty("java.io.tmpdir"));

  public static boolean isMultipartRequest(ServletRequest request) {
    return request.getContentType() != null
        && request.getContentType().startsWith(MULTIPART_FORMDATA_TYPE);
  }

  /**
   * If you want to have multipart support in your handler, call this method each time
   * your doHandle method is called (prior to calling getParameter).
   *
   * Servlet 3.0 include support for Multipart data with its
   * {@link HttpServletRequest#getPart(String)} & {@link HttpServletRequest#getParts()}
   * methods, but the spec says that before you can use getPart, you must have specified a
   * {@link MultipartConfigElement} for the Servlet.
   *
   * <p>
   * This is normally done through the use of the MultipartConfig annotation of the
   * servlet in question, however these annotations will not work when specified on
   * Handlers.
   *
   * <p>
   * The workaround for enabling Multipart support in handlers is to define the
   * MultipartConfig attribute for the request which in turn will be read out in the
   * getPart method.
   *
   * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=395000#c0">Jetty Bug
   *      tracker - Jetty annotation scanning problem (servlet workaround) </a>
   * @see <a href="http://dev.eclipse.org/mhonarc/lists/jetty-users/msg03294.html">Jetty
   *      users mailing list post.</a>
   */
  public static void enableMultipartSupport(HttpServletRequest request) {
    request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
  }

  @Override
  public void handle(String target, Request baseRequest, HttpServletRequest request,
      HttpServletResponse response) throws IOException, ServletException {
    boolean multipartRequest = HttpMethod.POST.is(request.getMethod())
        && isMultipartRequest(request);
    if (multipartRequest) {
      enableMultipartSupport(request);
    }

    try {
      super.handle(target, baseRequest, request, response);
    } finally {
      if (multipartRequest) {
        MultiPartInputStreamParser multipartInputStream = (MultiPartInputStreamParser) request
            .getAttribute(Request.__MULTIPART_INPUT_STREAM);
        if (multipartInputStream != null) {
          try {
            // a multipart request to a servlet will have the parts cleaned up correctly, but
            // the repeated call to deleteParts() here will safely do nothing.
            multipartInputStream.deleteParts();
          } catch (MultiException e) {
//            LOG.error("Error while deleting multipart request parts", e);
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这可以像:

MultipartConfigInjectionHandler multipartConfigInjectionHandler =
    new MultipartConfigInjectionHandler();

HandlerCollection collection = new HandlerCollection();
collection.addHandler(new SomeHandler());
collection.addHandler(new SomeOtherHandler());

multipartConfigInjectionHandler.setHandler(collection);

server.setHandler(multipartConfigInjectionHandler);
Run Code Online (Sandbox Code Playgroud)