【问题标题】:How can i display pdf in django which is stored in mysql database as blob?如何在 django 中显示存储在 mysql 数据库中的 pdf 作为 blob?
【发布时间】:2018-03-26 09:30:29
【问题描述】:

在我的 Web 应用程序中,用户可以上传一个 pdf 文件,并且该文件存储在 mysql 数据库本身中。该文件使用以下代码存储在数据库中。 注意:由于安全相关问题,文件保存在数据库中。

    data=request.FILES['file'].read()
    fcursor = db.cursor()
    fcursor.execute("INSERT INTO REPORTS(DOC,id) VALUES(%s,%s)",(data,id))
    db.commit()
    fcursor.close()
    db.close()

用户有权查看此 pdf。现在我在临时文件的帮助下将 pdf 传输到模板。

c = db.cursor()
c.execute("SELECT DOC FROM REPORTS WHERE id=%s",(id,))
file = c.fetchone()[0]
c.close()

f=tempfile.NamedTemporaryFile(dir='/tmp/',suffix='.pdf')
f.write(filename)
f.seek(0)
response = HttpResponse(f, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="report.pdf"'
return response

但实际上,我想直接从数据库中显示 pdf,而不使用临时文件。

【问题讨论】:

    标签: javascript python mysql django


    【解决方案1】:

    是的,我得到了答案!我不需要临时文件。当我通过响应传递从数据库读取的数据时,它起作用了。我误解了,在我们有存储文件之前它不会起作用。但现在我清楚了,我们必须将二进制数据与响应一起传递。由于数据库是pdf的二进制形式,所以从数据库和临时文件中读取的数据都是一样的。

    c = db.cursor()
    c.execute("SELECT DOC FROM REPORTS WHERE id=%s",(id,))
    file = c.fetchone()[0]
    c.close()
    
    response = HttpResponse(file, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="report.pdf"'
    return response
    

    【讨论】:

      【解决方案2】:

      我真的希望您有足够的理由将您的 .pdf 文件存储在数据库中。更好的做法是将上传的文档或图像存储在文件系统中,并将其文件路径或 URL 保存到数据库中的文件中。 您的问题类似于this one。问题可能与您从数据库中读取 pdf 文件的方式有关。要直接从数据库显示 pdf,您可以尝试使用 converted_file = open(file_from_db,"rb") 函数将您的 blob 文件作为二进制文件读取。然后你可以这样做: response = HttpResponse(converted_file, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="report.pdf"' return response

      【讨论】:

      • 是的,谢谢您的回复。我已经完成了。我想我不需要临时文件。在上面的代码中,我只是用响应而不是 f 传递了文件,因此它正在工作。
      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 2014-01-05
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2014-08-05
      相关资源
      最近更新 更多