How to use HttpServletRequest#getParts() in a servlet filter running on Tomcat?

后端 未结 2 1906
栀梦
栀梦 2020-11-29 09:52

I would like to upload a file in my JSF application. I am using a Filter and HttpServletRequestWrapper to access the upload file.

         


        
相关标签:
2条回答
  • 2020-11-29 10:18

    Also try Multipart filter. worked for me.

    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.eclipse.jetty.servlets.MultiPartFilter</filter-class>
    </filter> 
    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <servlet-name>CamelServlet</servlet-name> 
    </filter-mapping>
    
    0 讨论(0)
  • 2020-11-29 10:24

    In order to get HttpServletRequest#getParts() to work in a Filter in Tomcat, you need to set allowCasualMultipartParsing="true" in the webapp's <Context> element in Webapp/META-INF/context.xml or Tomcat/conf/server.xml.

    <Context ... allowCasualMultipartParsing="true">
    

    Because as per the servlet 3.0 specification the HttpServletRequest#getParts() should only be available inside a HttpServlet with the @MultipartConfig annotation. See also the documentation of the <Context> element:

    allowCasualMultipartParsing

    Set to true if Tomcat should automatically parse multipart/form-data request bodies when HttpServletRequest.getPart* or HttpServletRequest.getParameter* is called, even when the target servlet isn't marked with the @MultipartConfig annotation (See Servlet Specification 3.0, Section 3.2 for details). Note that any setting other than false causes Tomcat to behave in a way that is not technically spec-compliant. The default is false.

    See also:

    • Tomcat 7 issue 49711
    • Uploading files in Servlet 3.0
    • Uploading files in JSF 2.0 and Servlet 3.0

    Unrelated to the concrete problem, the following is definitely not right:

    byte[] b = new byte[(int) p.getSize()];
    p.getInputStream().read(b);
    params.put(p.getName(), new String[]{new String(b)});
    

    First, you are not respecting the character encoding specified by the client -if any. Second, this will fail for binary files.

    0 讨论(0)
提交回复
热议问题