0

I am sending formData to the backend using an object literal approach like so (which it has to be):

var formData = {};
formData.patentID = caseSelected.patentID;
formData.clientRef = data.clientRef;
formData.amendedDoc = data.amended.amendedDoc;

When the request is made, there is an error. When I review the request payload, the formData.amendedDoc isn't sending the attached PDF and instead provides an empty object like so:

enter image description here

If I log the formData just before sending in the http request, I can see that the PDF file is there

Question

How do I send the PDF document with the rest of the formData? Confused on Blobs and Base64 concepts/

Patrick McDermott
  • 1,220
  • 1
  • 15
  • 30
  • What error are you getting? – Naveen Chahar Nov 19 '20 at 16:54
  • I'm not. In the request payload, the `amendedDoc` property shows an empty object – Patrick McDermott Nov 20 '20 at 08:55
  • It depends on (a) What you are currently doing with the `formData` object and (b) What format the server side code expects the data to be received in. – Quentin Nov 20 '20 at 09:27
  • 2
    A Blob, in JS terms, is a type of in-memory object and can't be sent over HTTP without being encoded somehow. It is also distract from a BLOB type in a database which is what the tag — [tag:blob] — you used is about. – Quentin Nov 20 '20 at 09:28
  • Thanks for the help. So in less the database accepts Blobs, there's no reason to send it in Blob format? And could you elaborate on the encoded part? – Patrick McDermott Nov 20 '20 at 09:50
  • A JS blob and a data blob are completely different things with the same name. You can't dump raw data as arranged in memory over HTTP. It has to be represented as something HTTP supports (usually text). – Quentin Nov 20 '20 at 10:24

1 Answers1

1

You can't include file inside a JSON while making a request. Instead use FormData object to send to files along with other fields. Like this -

      var formData = new FormData();
      formData.append("patentID",caseSelected.patentID);
      formData.append("clientRef",data.clientRef);
      formData.append("amendedDoc",data.amended.amendedDoc);

Also do not forget to set the content-type of request to multipart/form-data ( Content-Type: multipart/form-data )

Naveen Chahar
  • 561
  • 3
  • 10
  • You can read this article for more information : https://javascript.info/formdata – Naveen Chahar Nov 20 '20 at 09:23
  • Thanks for the reply. I've set it to undefined as the browser automatically detects the correct type. I, unfortunately, am required to use the object literal `var formData = {}` – Patrick McDermott Nov 20 '20 at 09:48
  • If you want to use object literal then you can Base64 encode the file and then send it. Check out this post : https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript – Naveen Chahar Nov 20 '20 at 12:23