从JavaScript中的字节下载文件 [英] Download File from Bytes in JavaScript
本文介绍了从JavaScript中的字节下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从AJAX响应中下载以字节形式出现的文件。
I want to download the file which is coming in the form of bytes from AJAX response.
我试图在<$ c的帮助下这样做$ c> 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();
实际上是在下载pdf文件,但文件本身已损坏。
It is in fact downloading the pdf file but the file itself is corrupted.
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
我问了很长时间的问题,所以我某些细节可能有问题。
I asked the question long time age, so I might be wrong in some details.
Blob
因为结果需要数组缓冲区。这就是为什么base64字节需要首先转换为数组缓冲区的原因。
Blob
as it turned out needs array buffers. That's why base64 bytes need to be converted to array buffers first.
这是执行此操作的函数:
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;
}
这是我保存pdf文件的功能:
Here is my function to save a pdf file:
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);
这篇关于从JavaScript中的字节下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文