本文介绍了在 JavaScript 中从字节下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载来自 AJAX 响应的字节形式的文件.

I want to download the file which is coming in the form of bytes from AJAX response.

我尝试在 Bolb 的帮助下这样做:

I tried to do it this way with the help of 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 ago, so I might be wrong in some details.

事实证明,Blob 需要数组缓冲区.这就是为什么需要先将 base64 字节转换为数组缓冲区的原因.

It turns out that Blob 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 中从字节下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:15