How to process a multipart request consisting of a file and a JSON object in Spring restful service?

前端 未结 9 1175
一生所求
一生所求 2020-12-08 07:47

I have the following resource (implemented using Spring 4.05.RELEASE) which accepts a file and a JSON object:

(P.S. activityTemplate is a serializable entity class)<

相关标签:
9条回答
  • 2020-12-08 08:33

    Hope this should help you. You need to set the boundary in your request to inform the HTTP Request. is simple; A brief introduction to the multipart format can be found in the below link

    HTML 4.01 Specification for multipart

    The following example illustrates "multipart/form-data" encoding. If the Json Object is "MyJsonObj" , and file that need to be send is "myfile.txt", the user agent might send back the following data:

    Content-Type: multipart/form-data; boundary=MyBoundary
    
    --MyBoundary
    Content-Disposition: form-data; name="myJsonString"
    Content-Type: application/json
    
    MyJsonObj //Your Json Object goes here
    --MyBoundary
    Content-Disposition: form-data; name="files"; filename="myfile.txt"
    Content-Type: text/plain
    
    ... contents of myfile.txt ...
    --MyBoundary--
    

    or if your files is of type image with name "image.gif" then,

    --MyBoundary
    Content-Disposition: file; filename="image.gif"
    Content-Type: image/gif
    Content-Transfer-Encoding: binary
    
    ...contents of image.gif...
    --MyBoundary--
    

    You specify boundary in the Content-Type header so that the server knows how to split the data sent.

    So, you basically need to select a boundary value to:

    • Use a value that won't appear in the HTTP data sent to the server like 'AaB03x'.
    • Be consistent and use the same value all over the request.
    0 讨论(0)
  • 2020-12-08 08:41

    The error message indicates that there is no HttpMessageConverter registered for a multi-part/MIME part of content type: application/octet-stream. Still, your jarFile parameter is most likely correctly identified as application/octet-stream, so I'm assuming there's a mismatch in the parameter mapping.

    So, first try setting the same name for the parameter and the form's input element.

    Another problem is that the JSON is uploaded as a (regular) value of a text input in the form, not as a separate part in the multi-part/MIME. So there's no content-type header associated with it to find out that Spring should use the JSON deserializer. You can use @RequestParam instead and register a specific converter like in this answer: JSON parameter in spring MVC controller

    0 讨论(0)
  • 2020-12-08 08:46

    Couldn't you change your

    @RequestMapping(value="/create", method=RequestMethod.POST)
    

    to

    @RequestMapping(value="/create",
                    method=RequestMethod.POST, consumes ={"multipart/form-data"})
    
    0 讨论(0)
提交回复
热议问题