Posting a File and Associated Data to a RESTful WebService preferably as JSON

后端 未结 11 969
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:45

This is probably going to be a stupid question but I\'m having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON

11条回答
  •  孤独总比滥情好
    2020-11-22 11:32

    I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related request.

    The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.

    You can check RFC 2387 specification for more in-depth details.

    Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.

    Example:

    POST /upload HTTP/1.1
    Host: www.hostname.com
    Content-Type: multipart/related; boundary=xyz
    Content-Length: [actual-content-length]
    
    --xyz
    Content-Type: application/json; charset=UTF-8
    
    {
        "name": "Sample image",
        "desc": "...",
        ...
    }
    
    --xyz
    Content-Type: image/jpeg
    
    [image data]
    [image data]
    [image data]
    ...
    --foo_bar_baz--
    

提交回复
热议问题