简体   繁体   中英

Getting HttpServletRequest.getParts() to work with jersey

I have

@MultipartConfig(location="/tmp", fileSizeThreshold=1048576,
        maxFileSize=20848820, maxRequestSize=418018841)
@Path("/helloworld")
public class HelloWorld extends HttpServlet {

@POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    //@Consumes()
    @Produces("text/plain")
    public void doPost(@Context HttpServletRequest httpRequest) {
        System.out.println("pinged");
       //...
    }
}

and I want to access the parts and get the files. But when I do httpRequest.getPart("token") I get java.lang.IllegalStateException: Request.getPart is called without multipart configuration. How do i get this to work? I am using Jersey and I know there is a better way to do this with FormDataMultiPart but my goal is to write a function that takes a HttpServletRequest and extracts some data and turns it into a custom object. (The use of a jersey server here is purely random. I want my function to work with other java servers that my not have FormDataMultiPart but do have HttpServletRequest ).

First of all this is not how JAX-RS is supposed to be used. You don't mix the JAX-RS annotations with a Servlet. What you need to do is add the multipart config into the web.xml.

<servlet>
    <servlet-name>com.example.AppConfig</servlet-name>
    <load-on-startup>1</load-on-startup>
    <multipart-config>
        <max-file-size>10485760</max-file-size>
        <max-request-size>20971520</max-request-size>
        <file-size-threshold>5242880</file-size-threshold>
    </multipart-config>
</servlet>
<servlet-mapping>
    <servlet-name>com.example.AppConfig</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

Notice the servlet-name is the fully qualified class of the Application subclass.

And the rest I used to test

import javax.ws.rs.core.Application;

// if you're using `@ApplicationPath`, remove it
public class AppConfig extends Application {

}
@Path("upload")
public class FileUpload {
    @POST
    @Path("servlet")
    public Response upload(@Context HttpServletRequest request)
            throws IOException, ServletException {
        Collection<Part> parts = request.getParts();
        StringBuilder sb = new StringBuilder();
        for (Part part: parts) {
            sb.append(part.getName()).append("\n");
        }
        return Response.ok(sb.toString()).build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM