3

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?

OPV
  • 1
  • 26
  • 81
  • 156
  • It's unclear what you're asking. What do you mean by "attach file"? What do you think the differences are between sending a text file and sending textual data? – CodeCaster Jul 23 '17 at 11:18
  • Attach I mean send file in POST request together with text data. – OPV Jul 23 '17 at 11:31
  • That doesn't clarify your question. [Edit] it to show how you actually issue the request. – CodeCaster Jul 23 '17 at 11:32

2 Answers2

5

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

Tim
  • 76
  • 4
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
janmbaco
  • 330
  • 3
  • 10