问题
I have a REST service hosted inside Karaf, which is working fine with all requests except for multipart requests. I'm using the com.sun.jersey packages, as I have only succeeded in hosting these inside of Karaf to be accessed over HTTP.
When I try to receive the HttpServletRequest inside the POST and call the getParts() method on it, I get the error:
IllegalStateException: No multipart config for servlet
I have found that I am missing the @MultipartConfig annotation on my servlet, so I added this to the servlet implementation I am using. I extend com.sun.jersey.spi.container.servlet.ServletContainer
and add the annotation to that class. But this does not work.
I've also tried using my own extension of the HttpServlet
class, that reproduces the error:
@MultipartConfig
public class MultipartServlet extends HttpServlet {
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
try {
final HttpServletRequest httpRequest = (HttpServletRequest)request;
final Collection<Part> parts = httpRequest.getParts();
System.out.println("There are " + parts.size() + " parts");
}
catch (Exception exception) {
System.out.println("MEGA FAIL");
System.out.println(exception.getMessage());
}
super.service(request, response);
}
}
I've seen the approach using org.glassfish.jersey packages that makes registers the MultiPartFeature class with the ResourceConfig
, but I haven't been able to get these packages accessible over HTTP inside of Karaf (the services appear to register without error, but all requests return 404 responses).
回答1:
Instead of trying to use the Servlet multipart, you just use Jersey's multipart support. In the example in the link, it uses named parts. If you want to be able to process all unknown parts, you can just use FormDataMultiPart as the method parameter. This way you can access all the parts with getFields()
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response post(FormDataMultiPart multiPart) {
final Map<String, List<FormDataBodyPart>> = multiPart.getFields();
}
来源:https://stackoverflow.com/questions/45960689/jax-rs-multipart-with-com-sun-jersey