如何从atob创建二进制blob - 当前获得不同的字节

Joe*_*yre 3 javascript c# base64

我在服务器上创建了一个二进制Excel文件,我使用从JavaScript/JQuery $ ajax调用调用的Convert.ToBase64String(FileData)从C#WebMethod返回.我已经确认base64字符串数据到达客户端,但是当我尝试将其转换为二进制blob并保存时,保存到磁盘的字节与服务器上的字节不同.(我得到了很多0xC3等字节,看起来很像utf8双字节注入)

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

成功处理程序代码包括

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');
Run Code Online (Sandbox Code Playgroud)

当它完成下载时,它具有错误的字节值.与源的二进制比较显示它很接近,但是C3和类似的值插入或插入到位.

有没有什么我做错了或缺少让我的Base64字符串正确转换为客户端二进制blob?

Har*_*ind 9

新的Blob构造函数将它遇到的任何字符串编码为UTF-8(http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob).由于您正在处理二进制数据,因此将其转换为UTF-8多字节表示形式.

相反,您需要在传递给Blob构造函数之前将数据转换为字节数组.

以下代码适用于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])
Run Code Online (Sandbox Code Playgroud)

这就是说我不知道atob浏览器是否定义得很好(我猜是有一个原因,mozilla提供了更长的示例代码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).