我在服务器上创建了一个二进制 Excel 文件,我使用从 JavaScript/JQuery $ajax 调用调用的 Convert.ToBase64String(FileData) 从 C# WebMethod 返回。我已经确认 base64 字符串数据到达客户端,但是当我尝试将其转换为二进制 blob 并保存时,保存到磁盘的字节与服务器上的字节不同。 (我得到了很多 0xC3 等字节,看起来很像 utf8 双字节注入(inject))
$.ajax({
type: "POST",
contentType: "application/json;",
dataType: "json",
processData: false,
data: "{ inputData: \"" + dataString + "\" }",
url: "Api.aspx/GetExcel",
success: ...
成功处理程序代码包括:
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');
当它完成下载时,它有错误的字节值。与源代码的二进制比较显示它很接近,但插入或修改了 C3 和类似的值。
为了将我的 Base64 字符串正确转换为客户端二进制 blob,我是否做错了或遗漏了什么?
最佳答案
新的 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])
也就是说,我不知道 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 是有原因的)。
关于javascript - 如何从 atob 创建二进制 blob - 当前获取不同的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27239719/