Is it possible to attach file in POST Json?

杀马特。学长 韩版系。学妹 提交于 2019-12-07 12:12:27

问题


I have a heap of data in format JSON(Serialized object). I send this data to server by POST method with header: Content-Type: application/json.

Is it possible to attach file to body request and send at once. Or JSON data sugggests sending only text data?


回答1:


Try to send the file inside the json object as a base64 string:

{
"file":"dGhpcyBpcyBhIGZpbGUgc2FtcGxl..." 
}

Later you can open the file with something like:

document.location = 'data:application/pdf;base64,' + file



回答2:


In this context, the content-type header aims to describe the type of data in the request body. If you use application/json the server will expect a JSON body.

If your goal is to send a single request with a JSON object and a file, you can either encode the file in the JSON structure (Probably base64. See: Binary Data in JSON String. Something better than Base64)

{
  ...
  file: "encoded_content",
  ...
}

Or you can use the content type multipart/form-data. A multipart is a part containing other part. The first subpart may be the JSON strucuture. The second one may be the file



来源:https://stackoverflow.com/questions/45264447/is-it-possible-to-attach-file-in-post-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!