gpt4 book ai didi

javascript - Angular - 下载并显示 PDF

转载 作者:行者123 更新时间:2023-11-28 06:43:07 25 4
gpt4 key购买 nike

当前使用

https://github.com/stranger82/angular-utf8-base64

https://github.com/eligrey/FileSaver.js/

解码我从rest API获取的base64编码的PDF文件。

它解码和下载得很好,但是当我尝试查看它时,它是空白的。

我看过

AngularJS: Display blob (.pdf) in an angular app

并尝试添加

responseType: 'arraybuffer'

但是,对于我的获取请求,这会导致响应为空,并且获取请求不会返回任何数据。

其他文件似乎可以正常下载和渲染。

一如既往,我们将不胜感激任何帮助!

代码:

          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);
});

最佳答案

如果 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();
}
};
}
})();

关于javascript - Angular - 下载并显示 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com