AngularJs应用程序中的下载已损坏

vfs*_*aki 5 javascript download angularjs

我正在尝试使用FileSaver.js下载文件,但每当我点击下载按钮时,我都会收到损坏的文件.

App由PHP REST服务支持,并且从命令行使用cURL确认REST正常工作.

这是我用于下载的伪代码的最后一个版本:

// Let str be the data received from $http promise
// This code is run in a "then" callback

var arr= new Uint8Array(str.length);
for(var i=0; i<str.length; i++) {
    arr[b]=str.charCodeAt(i);
};
var blob = new Blob([arr], {type: 'application/octet-stream'});
saveAs(blob, "AFileName");
Run Code Online (Sandbox Code Playgroud)

它只会破坏文件.

我也试过没有应用Uint8Array,并str直接给予Blob.正如你猜测的那样,它也失败了.

我自己在写服务器和客户端,所以我可以更改其中的任何内容.但问题是我想处理客户端下载,我只是无法将用户重定向到文件URL以下载它,因为REST需要身份验证,而且该令牌只存在于Angular应用程序中.在没有身份验证的情况下更改服务器只是为了处理文件下载不是一个好的选择.

REST具有/files/:id访问时的URL ,将文件内容作为常规HTTP文件下载(如上所述使用cURL进行测试).可能$http是问题?以某种方式强制对接收的数据进行某种编码或某些假设.无论如何,我在Angular方面没有多少经验.

vfs*_*aki 6

我发现了这个问题.那是我 :)

我必须指定responseType: "arraybuffer"用于$http然后给str直接Blob.

固定代码

// Let str be the data received from $http promise
// This code is run in a "then" callback
// Make sure to specify "responseType: "arraybuffer"" for $http

var blob = new Blob([str], {type: 'application/octet-stream'});
saveAs(blob, "AFileName");
Run Code Online (Sandbox Code Playgroud)

responseType在错误的地方改变了.