Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to attach file in POST Json?

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?

like image 269
OPV Avatar asked Jan 21 '26 02:01

OPV


2 Answers

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

like image 183
Tim Avatar answered Jan 23 '26 21:01

Tim


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
like image 23
janmbaco Avatar answered Jan 23 '26 19:01

janmbaco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!