使用FileSaver.js从Azure Blob存储中下载损坏的文件

时间:2017-03-16 18:17:09

标签: angular azure-blob-storage filesaver.js

我在Azure中有一个Excel电子表格,我使用SAS公开,在下载后,它说该文件已损坏。这是保存和uri的代码

var result : any= {};
result.fileUri =
    "https://mystorageaccount.blob.core.windows.net/market-files/33b55b3c-8997-405c-af31-33f6f3e79daf?sv=2016-05-31&sr=b&sig=5Xw%2F4UPcdXbXrxd4mIcZUPQX%2FZzVZfDTQoTfr5V6NTY%3D&st=2017-03-16T18%3A00%3A12Z&se=2017-03-17T18%3A05%3A12Z&sp=rw";

this.http.get(result.fileUri).subscribe(
             (response: any) => {
                                 var mediaType = 'application/octet-stream';
                                 var blob = new Blob([response._body], { type: mediaType });
                                 var filename = 'test.xlsx';
                                 saveAs(blob, filename);
            });

使用正确的文件名下载文件但是当我打开它时,我在Excel中收到一条错误,说文件已损坏。

1 个答案:

答案 0 :(得分:0)

我不是Angular2的专家,但我相信应该将响应主体转换为arraybuffer。关于如何处理它,你可以在SO上阅读this post

以下是使用普通Javascript和FileSaver.js从Azure Blob存储下载文件的示例。

var fileUri = "https://storageaccount.blob.core.windows.net/market-files/<bolbNameAndSAS>";
var oReq = new XMLHttpRequest();
oReq.open("GET", fileUri, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
    var blob = new Blob([oReq.response], {type: "application/octet-stream"});
    var filename = 'test.xlsx';
    saveAs(blob, filename);
};

oReq.send();