0

Since my javascript program is going to upload documents to the server using the FormData object, and the documents are in base64 format, I need to convert a base64 string to a byte array, and this link seems to be the correct one for that:

Convert base64 string to ArrayBuffer:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

Unfortunately, my program depends on an older version of javascript which doesn't define Uint8Array. Does anyone know if there's a alternative way of accomplishing what I want or if there is an alternative to Uint8Array that I can use?

thanks

Hank Rearden
  • 87
  • 1
  • 1
  • 10

1 Answers1

0

Unluckly it seems that you don't have access to TypedArrays and their buffers, so you can use a simple array.

function _base64ToArray(base64) {
    var binary_string = window.atob(base64);
    var bytes = [];
    for (var i = 0; i < binary_string.length; i++) {
        bytes.push(binary_string.charCodeAt(i));
    }
    return bytes;
}

Using an array is it not the same as a buffer, but I hope this can solve your problem anyway.

DDomen
  • 1,808
  • 1
  • 7
  • 17
  • Thanks DDomen, but unfortunately I cannot pass the value returned from _base64ToArray to the FormData as I get this: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'. – Hank Rearden Feb 05 '21 at 22:25
  • You need to wrap the array as a Blob befor sending it through your Ajax, just do `request.send(new Blob(_base64ToArray(array)))` – DDomen Feb 05 '21 at 22:32
  • Also check if [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) is available, you can also substitute Uint8Array with it. – DDomen Feb 05 '21 at 22:33
  • @HankRearden I saw your edit, you should pass the array directly, and have you also tried to set options of the blob? Maybe like this `new Blob(value2, { type: 'image/png' })`? Otherwise you can build the Blob directly from the `binary_string` argument of the `_base64ToArray`, like `new Blob([ binary_string ], { type: 'image/png' })`. See also [Blob MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob). – DDomen Feb 06 '21 at 15:15
  • Thanks but when changing the code to requestBody.append(parameter.Name, new Blob(value2, { type: 'image/png' }), "hank.png"); the generated file contains something like 2552162552240167470737001010960960025525... just an sequence of numbers. I guess that the blob just doesn't work with bytearrays but only with ArrayBuffer and TypesArrays :-( – Hank Rearden Feb 06 '21 at 20:37