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?

POV
  • 11,293
  • 34
  • 107
  • 201
  • 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. – POV 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
  • 340
  • 4
  • 11
  • Then how to handle `file` in server side? If it is in base54 string? It will be POST field? – POV Jul 23 '17 at 11:48
  • well, in your case you can use `multipart/form-data` to send the file to the server. – janmbaco Jul 23 '17 at 11:55
  • 1
    So, this is header `multipart/form-data `? also use content-type: application/json? – POV Jul 23 '17 at 13:17