通过HTML5文件和URL API正确创建和提供PDF Blob

时间:2013-03-17 23:53:09

标签: javascript html5 file blobs

好吧,假设我将文档数据存储在某个地方,让我们任意选择this pdf

问题#1。我想要做的是对此URL进行AJAX调用(因为我需要传递一些身份验证标头,它是跨域的)。然后获取返回的数据,为其创建blob url,将iFrame附加到DOM,并将src定向到blob网址。

目前我的代码如下:

$.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中显示,不知道如何保证这一点。

3 个答案:

答案 0 :(得分:38)

jQuery.ajax目前不支持blob,请参阅此bug report #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'
})...

答案 1 :(得分:0)

我已经使用@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();

答案 2 :(得分:0)

var src_url = your url here;
var contentDisposition = 'AlwaysInline';
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');

这样做,您将可以查看pdf而不是下载它,<​​/ p>

Header ContentDisposition应该为'AlwaysInline',然后仅显示文件而不是下载文件。