Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a binary file using fetch

I'm trying to upload a file to Zendesk, here is the API:

curl "https://{subdomain}.zendesk.com/api/v2/uploads.json? 
filename=myfile.dat&token={optional_token}" \
-v -u {email_address}:{password} \
-H "Content-Type: application/binary" \
--data-binary @file.dat -X POST

This is how my code looks like while file is a File object I'm getting from a dropzone:

const formData = new FormData();
formData.append("file", file);

fetch(
  "https://{my-domain}.zendesk.com/api/v2/uploads.json?filename=" + file.name,
  {
    method: "POST",
    body: formData
  }
)

The problem is that the final file is corrupted because of WebKitFormBoundary header and footer.

This is what I tried:

  1. Setting "Content-Type: application/binary" header as this is what the API expect.

  2. Passing the file to the fetch body without FormData (as-is).

  3. Using FileReader.readAsBinaryString before passing it to the body.

None of my attempts worked - the server returned error, the only way I was able to create a file is with the FormData and without any Content-Type header but I didn't find a way to get rid of the WebKitFormBoundary header and footer.

For example:

------WebKitFormBoundaryragq26qGRKa2B9Qg
Content-Disposition: form-data; name="file"; filename="README.md"
Content-Type: text/markdown


------WebKitFormBoundaryragq26qGRKa2B9Qg--
like image 475
Roni Hacohen Avatar asked Aug 12 '26 19:08

Roni Hacohen


1 Answers

The following code worked for me:

fetch(
  "https://{my-domain}.zendesk.com/api/v2/uploads.json?filename=" + file.name,
  {
   method: "POST",
   body: file,
   headers: {
    "Content-type": file.type
   }
  }
 )
like image 65
Roni Hacohen Avatar answered Aug 14 '26 23:08

Roni Hacohen