好吧,假设我在某个地方存储了文档数据,让我们任意取这个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中。
jQuery.ajax当前不支持Blob,请参阅此错误报告#7248,该报告已关闭为wontfix。
然而,在没有jQuery:的情况下很容易对Blob执行XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
// Note: .response instead of .responseText
var blob = new Blob([this.response], {type: 'application/pdf'}),
url = URL.createObjectURL(blob),
_iFrame = document.createElement('iframe');
_iFrame.setAttribute('src', url);
_iFrame.setAttribute('style', 'visibility:hidden;');
$('#someDiv').append(_iFrame)
}
};
xhr.send();
可耻地从HTML5rocks复制。
如果jQuery确实支持Blob类型,那么它可以简单到:
$.ajax({
url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf',
dataType:'blob'
})...
我使用@Ciantic答案来调整我的答案。我避免使用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();
var src_url = your url here;
var contentDisposition = 'AlwaysInline';
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');
通过这样做,你将能够查看pdf而不是下载它,
Header ContentDisposition应该是"AlwaysOnline",然后它只显示您的文件而不是下载它。