目前正在使用
https://github.com/stranger82/angular-utf8-base64
和
https://github.com/eligrey/FileSaver.js/
解码我从其他API获取的base64编码的PDF文件。
它解码并下载得很好,但是当我尝试查看它时,它是空白的。
我看了
AngularJS: Display blob (.pdf) in an angular app
并尝试添加
responseType: 'arraybuffer'
但是,对于我的get请求,这会导致响应为null,而不会从get请求返回任何数据。
其他文件似乎下载并呈现得很好。
任何帮助都会一如既往地受到赞赏!
代码:
function save() {
var fileContent = base64.decode(response.File.fileContent);
var file = new Blob([fileContent], {type: response.File.contentType});
saveAs(file, response.File.name);
}
$http.get(url.join('')).success(function(response) {
save(response);
}).error(function(error) {
console.log('The following error has occured' + error);
});
答案 0 :(得分:0)
如果API Rest检索字节数组,则可以简单地使用此js函数
OBS:data.payload必须为字节数组 调用函数: DownloadService.download(data.payload,'downloadExcel','xls'); DownloadService.download(data.payload,'downloadPDF','pdf');
(function() {
'use strict';
angular
.module('fileUtils')
.service('DownloadService', DownloadService);
DownloadService.$inject = ['$window'];
function DownloadService($window) { // jshint ignore:line
this.download = function (fileBytes, name, type) {
var fileName = '';
if (name) {
fileName = name + '.' + type;
} else {
fileName = 'download.' + type;
}
var byteCharacters = atob(fileBytes);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/' + type });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = fileName;
document.body.appendChild(a);
a.click();
}
};
}
})();