How to create a binary blob from atob - currently getting different bytes

I have a binary Excel file generated on the server that I am returning from C # WebMethod using Convert.ToBase64String (FileData) called from JavaScript / JQuery $ ajax call. I have confirmed that the base64 string data is getting to the client, but when I try to convert it to a binary block and store it, the bytes stored on disk are not the same as on the server. (I get a lot of 0xC3 bytes, etc., which looks suspicious like doubled utf8 bytes)

$.ajax({
    type: "POST",
    contentType: "application/json;",
    dataType: "json",
    processData: false,
    data: "{ inputData: \"" + dataString + "\" }",
    url: "Api.aspx/GetExcel",
    success: ...

      

Success handler code includes:

var excelBlob = new Blob([atob(msg.d)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
...
var a = document.createElement('a');
...
a.href = window.URL.createObjectURL(excelBlob);
a.setAttribute('download', 'Excel.xlsx');

      

When it finishes downloading, it has the wrong byte values. Binary comparison to source shows it is close but has C3 and similar values โ€‹โ€‹inserted or tagged in place.

Is there something I am doing wrong or missing to get the Base64 string correctly converted to a binary blob client?

+3


source to share


1 answer


The new Blob constructor encodes any strings it encounters as UTF-8 ( http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob ). Since you are dealing with binary data, this is converted to multibyte UTF-8 representations.

Instead, you need to convert your data to a byte array before moving on to the Blob constructor.

The following code works for me in Chrome:



var binary = atob(base64)
var array = new Uint8Array(binary.length)
for( var i = 0; i < binary.length; i++ ) { array[i] = binary.charCodeAt(i) }
new Blob([array])

      

This says that I don't know how well it atob

renders in browsers (I guess the reason is that mozilla provides much longer example code https://developer.mozilla.org/en-US/docs/Web/API/ WindowBase64 / Base64_encoding_and_decoding # Solution_.232_.E2.80.93_rewriting_atob% 28% 29_and_btoa% 28% 29_using_TypedArrays_and_UTF-8 ).

+7


source







All Articles