1

I have a binary file I want to send in a multipart/form-data POST request. I want to include the binary in my javascript so I found a javascript function to convert a base64 string to a blob, it is below.

var b64data = 'blablabla';
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
const contentType = 'application/x-gzip';
const payload = b64toBlob(b64data, contentType);

I then use that blob as part of a multipart/form-data send with XMLHttpRequest. The relevant code is:

function fileUpload(url, fileData, fileName, nameVar, ctype) {
    var fileSize = fileData.length,
        boundary = "ABCDEFGHIFD",
        xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary);

    var body = "--" + boundary + "\r\n";
    body += 'Content-Disposition: form-data; name="' + nameVar +'"; filename="' + fileName + '"\r\n';
    body += "Content-Type: " + ctype + "\r\n\r\n";
    //body += fileData;
    end = "\r\n--" + boundary + "--";

    //var body = fileData;
    xhr.send(body + fileData + end);
    return true;
}

When I feed payload into the function like fileUpload(url,payload,fileName,nameVar,ctype);, the part that should be binary data just transfers as [object Blob]. If I take out the body and only send the fileData,

var body = fileData;
xhr.send(body);

It transfers the binary data in the packet.

Why is the first function not sending the binary through?

D3l_Gato
  • 1,297
  • 2
  • 17
  • 25
  • `body + fileData` is string concatenation, i.e. it converts `fileData` to a string. Are you able to use [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instead? – Ry- May 24 '19 at 23:43
  • Thanks Ry. This doc says I can only use blob, bytearray and file object https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data – D3l_Gato May 25 '19 at 00:07
  • I am trying to replicate this answer https://stackoverflow.com/questions/55749442/sending-javascript-post-xmlhttprequest-file-contents-in-hex/55753044#comment99212048_55753044 – D3l_Gato May 25 '19 at 00:08
  • That doc is missing `FormData`. – Ry- May 25 '19 at 00:11
  • If you want to make an answer I will accept it. This works. thank you so much. – D3l_Gato May 25 '19 at 00:32

0 Answers0