问题
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