【问题标题】:Flask - Generated PDF can be viewed but cannot be downloadedFlask - 生成的 PDF 可以查看但不能下载
【发布时间】:2020-09-01 12:34:34
【问题描述】:

我最近开始学习烧瓶并创建了一个简单的网络应用程序,它可以根据用户输入随机生成 PDF 格式的儿童数学作业表。

PDF 会在浏览器中自动打开并且可以查看。但是当我尝试在 PC 和 Chrome iOS 上下载它时,我收到错误消息(Chrome PC:失败 - 网络错误/Chrome iOS:此时无法下载文件)。

您可以在这里试用:kidsmathsheets.com

我怀疑这与我生成和返回 PDF 文件的方式有关。仅供参考,我正在使用 ReportLab 生成 PDF。我的代码如下(托管在 pythonanywhere 上):

from reportlab.lib.pagesizes import A4, letter
from reportlab.pdfgen import canvas
from reportlab.platypus import Table
from flask import Flask, render_template, request, Response
import io
from werkzeug import FileWrapper

# Other code to take in input and generate data

    filename=io.BytesIO()

    if letter_size:
        c = canvas.Canvas(filename, pagesize=letter)
else:
    c = canvas.Canvas(filename, pagesize=A4)

pdf_all(c, p_set, answer=answers, letter=letter_size)
c.save()
filename.seek(0)
wrapped_file = FileWrapper(filename)

return Response(wrapped_file, mimetype="application/pdf", direct_passthrough=True)

else:
    return render_template('index.html')

知道是什么导致了这个问题吗?非常感谢您的帮助!

【问题讨论】:

  • 您是否尝试过使用send_file
  • 是的,我试过 send_file() 并得到相同的错误消息...
  • 我相信这可能与 Chrome 安全设置有关:windowsreport.com/failed-network-error-download-chrome。我在 Firefox 中尝试了 PDF 下载,它可以工作,但在 Chrome(在 linux 上)中以同样的方式失败了
  • 谢谢格伦。我有一台 Windows 机器,它在 Microsoft Edge 上也失败了。因此,我认为我提供 PDF 的方式存在问题,导致此类错误。通常如果可以显示PDF,下载它应该是直截了当的......
  • 现在 Edge 不都是基于 Chrome 的吗?

标签: flask pythonanywhere


【解决方案1】:

请检查您是否使用 ajax POST 请求来调用端点来生成数据并分别显示 PDF。如果是这种情况 - 很可能这会导致我们观察到的行为。您可能想尝试使用对/my-endpoint/some-hashed-non-reusable-id-of-my-document 的GET 请求调用端点,其中some-hashed-non-reusable-id-of-my-document 将告诉端点要提供哪个文档,而不允许用户猜测您可能拥有的其他文档。你可以先试试:

@app.route('/display-document/<document_id>'):
def display_document(document_id):
    document = get_my_document_from_wherever_it_is(document_id)
    binary = get_binary_data_from_document(document)
    .........
    
    Prepare response here
    .......
    return send_file(binary, mimetype="application/pdf")

请注意:右键单击并“打印到 pdf”会起作用,但这不是我们想要的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2021-04-11
    • 2012-10-29
    • 2016-07-23
    • 2011-09-10
    相关资源
    最近更新 更多