Eri*_* H. 21 javascript html5 file blobs
好的,假设我将文档数据存储在某个地方,让我们任意选择这个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);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,我在iFrame中遇到了"无法渲染PDF"的问题.
问题#2.我希望这会导致文件下载提示.鉴于PDF自然只会在iFrame中显示,因此不确定如何保证这一点.
Cia*_*tic 38
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();
Run Code Online (Sandbox Code Playgroud)
从HTML5rocks无耻地复制.
如果jQuery确实支持Blob类型,它可以像下面这样简单:
$.ajax({
url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf',
dataType:'blob'
})...
Run Code Online (Sandbox Code Playgroud)