使用javascript下载时,PDF为空白 [英] PDF is blank when downloading using javascript
问题描述
我有一个Web服务,在其响应中返回PDF文件内容。我想在用户点击链接时将其下载为pdf文件。我在UI中编写的javascript代码如下:
I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written in UI is as follows:
$http.get('http://MyPdfFileAPIstreamURl').then(function(response){
var blob=new File([response],'myBill.pdf',{type: "text/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myBill.pdf";
link.click();
});
'response'包含来自'MyPdfFileAPIstreamURl'的servlet输出流的PDF字节数组。并且流也没有加密。
'response' contains the PDF byte array from servlet outputstream of 'MyPdfFileAPIstreamURl'. And also the stream is not encrypted.
因此,当我点击链接时,成功下载的PDF文件大小约为200KB。但是当我打开这个文件时,它会打开空白页面。下载的pdf文件的起始内容在图片中。
So when I click the link, a PDF file gets downloaded successfully of size around 200KB. But when I open this file, it opens up with blank pages. The starting content of the downloaded pdf file is in the image.
我无法理解这里有什么问题。帮助!
I can't understand what is wrong here. Help !
这是下载的pdf文件起始内容:
This is the downloaded pdf file starting contents:
推荐答案
通过XMLHttpRequest和 xhr.responseType ='arraybuffer'解决;
code:
solved it via XMLHttpRequest and xhr.responseType = 'arraybuffer';
code:
var xhr = new XMLHttpRequest();
xhr.open('GET', './api/exportdoc/report_'+id, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:"application/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Report_"+new Date()+".pdf";
link.click();
}
};
xhr.send();
这篇关于使用javascript下载时,PDF为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!