在AngularJs应用程序中损坏的下载 [英] Corrupted download in AngularJs app
问题描述
我正在尝试使用 FileSaver.js ,但是当我点击下载按钮时,我会收到一个损坏的文件。
I am trying to download a file using FileSaver.js, but I get a corrupted file whenever I hit download button.
应用程序由PHP REST服务和使用命令行中的cURL确认REST工作正常。
App is backed by a PHP REST service, and using cURL from command line confirms that REST is working OK.
这是我用于下载的最后一个伪代码版本:
Here is last version of pseudo-code that I use for downloading:
// 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");
它只是破坏文件。
也尝试没有应用 Uint8Array
,并将 str
直接发送到 Blob
。你猜到,它也失败了。
I also tried without applying the Uint8Array
, and giving str
directly to Blob
. As you guessed, it failed too.
我正在自己编写服务器和客户端,所以我可以改变任何东西。但是,我想要处理下载客户端的事情,我只是不能将用户重定向到文件URL进行下载,因为REST需要身份验证,并且该令牌只存在于Angular应用程序中。更改服务器只是为了处理文件下载而不进行身份验证不是一个不错的选择。
I am writing server and client myself, so I can change anything in them. But the thing is I want to handle downloads client-side, and I just can't redirect users to file URL to download it, because REST needs authentication and that token only lives within Angular app. It would not be a good choice to change server just to handle file downloads without authentication.
REST具有如 / files /:id
这样的URL,当访问时,将文件内容作为常规HTTP文件下载(如上所述用cURL测试)。可能是 $ http
的问题?不知何故强迫某种编码或接收数据的一些假设。无论如何,我没有太多的经验。
The REST has URLs like /files/:id
that when accessed, gives file content as a regular HTTP file download (tested with cURL as said above). Could $http
be the problem? Somehow forcing some kind of encoding or some assumptions on received data. I don't have much experience in Angular, anyway.
推荐答案
我发现了这个问题。这是我:)
I have found the problem. It was me :)
我必须指定 responseType:arraybuffer
for $然后将
str
直接发送给 Blob
。
I had to specify responseType: "arraybuffer"
for $http
then give str
directly to 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");
我正在更改 responseType
在错误的地方。
I was changing responseType
in wrong place.
这篇关于在AngularJs应用程序中损坏的下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!