@RequestPart with mixed multipart request, Spring MVC 3.2

前端 未结 5 769
长发绾君心
长发绾君心 2020-12-25 13:26

I\'m developing a RESTful service based on Spring 3.2. I\'m facing a problem with a controller handling mixed multipart HTTP request, with a Second part with XMLor JSON form

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 13:52

    I have managed to solve the problem

    Endpoint example:

    @PostMapping("/")
    public Document create(@RequestPart Document document,
                           @RequestPart(required = false) MultipartFile file) {
        log.debug("#create: document({}), file({})", delegation, file);
        //custom logic
        return document;
    }
    

    Exception:

    "error_message": "Content type 'application/octet-stream' not supported"
    

    Exception is thrown from the next method:

    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(HttpInputMessage,MethodParameter,Type)
    

    Solution:

    We have to create custom converter @Component, which implements HttpMessageConverter or HttpMessageConverter and knows about MediaType.APPLICATION_OCTET_STREAM. For simple workaround it's enough to extend AbstractJackson2HttpMessageConverter

    @Component
    public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {
    
    /**
     * Converter for support http request with header Content-Type: multipart/form-data
     */
    public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper, MediaType.APPLICATION_OCTET_STREAM);
    }
    
    @Override
    public boolean canWrite(Class clazz, MediaType mediaType) {
        return false;
    }
    
    @Override
    public boolean canWrite(Type type, Class clazz, MediaType mediaType) {
        return false;
    }
    
    @Override
    protected boolean canWrite(MediaType mediaType) {
        return false;
    }
    }
    

提交回复
热议问题