【问题标题】:jquery ajax not serving pdf filejquery ajax不提供pdf文件
【发布时间】:2016-10-22 21:25:30
【问题描述】:

我正在尝试使用 jquery、ajax 和 django 下载 pdf 文件。

我的 django views.py:

if request.POST.get('action') == 'download_labels':
    order_list = json.loads(request.POST.get('order_dict'), None)
    PackedOrders(dbname, order_list).downloadLabels()
    file = open('shipping_labels.pdf','rb')
    response = HttpResponse(file, content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename=shipping_labels.pdf"
    os.system('rm shipping_labels.pdf')
    return HttpResponse(response, content_type='application/pdf')

我的 ajax 查询:

data : {action:'download_labels',
        order_dict:JSON.stringify($checkedRows)},

success : function(response, status, request) {
    var file = new Blob([response], {type: 'application/pdf'});
    var fileURL = window.URL.createObjectURL(file);
    window.open(fileURL,'_blank');
},

ajax 将文件作为二进制数据响应返回并在新选项卡中打开它。但我在新标签中看到的只是空白页。空白页数等于原始pdf文件的页数。

在控制台中我看到了这个:

Error: Invalid XRef stream header
...
Warning: Indexing all PDF objects
pdf.worker.js (line 235)
<System>
PDF 85b859244e496561d60d217869d5d38a [1.3 - / -] (PDF.js: 1.3.76)
Error: Bad FCHECK in flate stream: 120, 239
...

Here 是完整的日志文件。

【问题讨论】:

    标签: javascript jquery ajax django pdf


    【解决方案1】:

    我不是 jQuery 专家,但我认为 jQuery ajax 不支持 blob。在文档中它只列出了这些数据类型:xml、json、script 或 html。 但是,我能够在不使用 jQuery 和使用带有纯 JavaScript 的 ajax 和这段代码的情况下使用此功能,

    我的 JavaScript(我也会为此添加错误处理)

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/pdf_test', true);
    xhr.responseType = 'blob';
    
    xhr.onload = function(e) {
      if (this.status == 200) {
        var blob = new Blob([this.response], {type: 'application/pdf'}),
        fileURL = URL.createObjectURL(blob);
        window.open(fileURL,'_blank');
      }
    };
    
    xhr.send();
    

    我的 django 视图(我也会为此添加错误处理)

    def pdf_test(request):
        pdf_file = open(r'C:\Pdfs\calculation_of_semiconductor_failure_rates.pdf', 'rb')
        response = HttpResponse(pdf_file, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="shippinglabels.pdf"'
        return response
    

    最重要的是,如果您不需要在新选项卡中打开而只需下载文件,那么您可以完全避免使用 ajax/Javascript,而只使用 HTML,这是一种更简单的方法

    &lt;a id="pdf-test" href="/pdf_test"&gt;Download PDF&lt;/a&gt;

    为了获得荣誉和进一步阅读,我使用了这些链接

    jQuery Ajax

    StackOverflow question

    Introduction to JavaScript Blobs and File Interface

    【讨论】:

      猜你喜欢
      • 2015-03-27
      • 2011-01-11
      • 2011-11-26
      • 2016-04-07
      • 1970-01-01
      • 2013-07-23
      • 2023-03-16
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多