application/x-www-form-urlencoded or multipart/form-data?

前端 未结 6 1544
無奈伤痛
無奈伤痛 2020-11-21 06:35

In HTTP there are two ways to POST data: application/x-www-form-urlencoded and multipart/form-data. I understand that most browsers are only able t

6条回答
  •  时光取名叫无心
    2020-11-21 07:16

    I don't think HTTP is limited to POST in multipart or x-www-form-urlencoded. The Content-Type Header is orthogonal to the HTTP POST method (you can fill MIME type which suits you). This is also the case for typical HTML representation based webapps (e.g. json payload became very popular for transmitting payload for ajax requests).

    Regarding Restful API over HTTP the most popular content-types I came in touch with are application/xml and application/json.

    application/xml:

    • data-size: XML very verbose, but usually not an issue when using compression and thinking that the write access case (e.g. through POST or PUT) is much more rare as read-access (in many cases it is <3% of all traffic). Rarely there where cases where I had to optimize the write performance
    • existence of non-ascii chars: you can use utf-8 as encoding in XML
    • existence of binary data: would need to use base64 encoding
    • filename data: you can encapsulate this inside field in XML

    application/json

    • data-size: more compact less that XML, still text, but you can compress
    • non-ascii chars: json is utf-8
    • binary data: base64 (also see json-binary-question)
    • filename data: encapsulate as own field-section inside json

    binary data as own resource

    I would try to represent binary data as own asset/resource. It adds another call but decouples stuff better. Example images:

    POST /images
    Content-type: multipart/mixed; boundary="xxxx" 
    ... multipart data
    
    201 Created
    Location: http://imageserver.org/../foo.jpg  
    

    In later resources you could simply inline the binary resource as link:

    
    
    

提交回复
热议问题