在 JavaScript 中从字节下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35038884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download File from Bytes in JavaScript
提问by Jahongir Rahmonov
I want to download the file which is coming in the form of bytes from AJAX response.
我想从 AJAX 响应下载以字节形式出现的文件。
I tried to do it this way with the help of Bolb
:
我尝试在以下人员的帮助下这样做Bolb
:
var blob=new Blob([resultByte], {type: "application/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.pdf";
link.click();
It is in fact downloading the pdf file but the file itself is corrupted.
它实际上是在下载 pdf 文件,但文件本身已损坏。
How can I accomplish this?
我怎样才能做到这一点?
回答by Jahongir Rahmonov
I asked the question long time ago, so I might be wrong in some details.
我很久以前就问过这个问题,所以我可能在某些细节上错了。
It turns out that Blob
needs array buffers. That's why base64 bytes need to be converted to array buffers first.
事实证明,这Blob
需要数组缓冲区。这就是为什么需要首先将 base64 字节转换为数组缓冲区的原因。
Here is the function to do that:
这是执行此操作的函数:
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
Here is my function to save a pdf file:
这是我保存pdf文件的功能:
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
};
Here is how to use these two functions together:
下面是如何一起使用这两个函数:
var sampleArr = base64ToArrayBuffer(data);
saveByteArray("Sample Report", sampleArr);
回答by KrishnaSingh
You just need to add one extra line and it should work. Your response is byte array from your server application
您只需要添加一行额外的行就可以了。您的响应是来自您的服务器应用程序的字节数组
var bytes = new Uint8Array(resultByte); // pass your byte response to this constructor
var blob=new Blob([bytes], {type: "application/pdf"});// change resultByte to bytes
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.pdf";
link.click();
回答by guest271314
Set Blob
type
at Blob
constructor instead of at createObjectURL
设置Blob
type
在Blob
构造函数而不是 atcreateObjectURL
var blob = new Blob([resultByte], {type: "application/pdf"});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "myFileName.pdf";
link.click();