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

前端 未结 9 1221
一生所求
一生所求 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.

提交回复
热议问题