我有角度函数从服务器获取pdf数据:
printDocument: function (bundleId, policyId) {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
$resource(baseUrlPrint, {
bundleId: bundleId,
policyId: policyId
}, {
get: {
method: 'GET'
},
responseType:'arraybuffer',
cache: true
}).get().$promise.then(function(result) {
console.log(result);
var file = new Blob([result], {type: 'application/pdf'});
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
}
当我检查结果变量时,我看到有字节数组包含pdf文件。但是当我在Notepad ++中打开这个文件时,我发现没有pdf字节数据,只有:[object Object]。我的Blob对象有问题吗?
如果API Rest检索字节数组,您只需使用此js函数即可
(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();
}
};
}
})();