好的,假设我在某个地方存储了文档数据,让我们任意取this pdf。
问题#1.我想做的是对这个URL进行AJAX调用(因为我需要传递一些身份验证头,而它是跨域的)。然后获取返回的数据,为其创建一个blob url,将iFrame附加到DOM,并将src
定向到blob url。
目前,我的代码如下所示:
$.ajax({
url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf'
}).done(function(data){
var file = new Blob([data], {type:'application/pdf'}),
url = URL.createObjectURL(file),
_iFrame = document.createElement('iframe');
_iFrame.setAttribute('src', url);
_iFrame.setAttribute('style', 'visibility:hidden;');
$('#someDiv').append(_iFrame);
});
不幸的是,我在iFrame中得到了一个‘渲染PDF失败’。
问题#2.我希望这会导致一个文件下载提示。不确定如何保证这一点,因为PDF的将自然地显示在iFrame中。
发布于 2019-02-07 16:46:51
我已经使用了@Ciantic answer来调整我的答案。我避免使用iframe obj,用户可以直接从页面下载文件。
var link = 'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf';
$("body").addClass("loading"); // adding the loading spinner class
var xhr = new XMLHttpRequest();
xhr.open('GET',link,true);
xhr.responseType = 'blob';
xhr.onload = function(e){
if (this.status == 200) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(new Blob([this.response], {type: 'application/pdf'}));
a.href = url;
a.download = 'report.pdf';
a.click();
window.URL.revokeObjectURL(url);
$('body').removeClass("loading"); //removing the loading spinner class
}else{
$('body').removeClass("loading") //removing the loading spinner class
console.log(this.status);
alert('Download failed...! Please Try again!!!');
}
};
xhr.send();
发布于 2019-05-16 19:03:09
var src_url = your url here;
var contentDisposition = 'AlwaysInline';
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');
通过这样做,您将能够查看pdf而不是下载它,
标题ContentDisposition应该是'AlwaysInline‘,然后它才会显示你的文件,而不是下载它。
https://stackoverflow.com/questions/15467747
复制相似问题