【问题标题】:Downloading file from FileField in Django with a HTTP link in a HTML file使用 HTML 文件中的 HTTP 链接从 Django 中的 FileField 下载文件
【发布时间】:2016-11-10 08:54:35
【问题描述】:

我创建了一个链接,当用户按下它时,它将从 Django 的媒体文件夹中下载一个 pdf 文件到用户的机器上。

我尝试了不同的方法,但对我来说都是错误的。它告诉我找不到文件,或者代码正在运行但文件已损坏。

我的 Html 链接:

<td>  <a href="/download/">Download</a></td>

我的 url 模式链接到一个视图中:

url(r'^download/$', views.DownloadPdf),

我的 FileField 是这样的:

upload_pdf = models.FileField()

以下 sn-p 代码是下载损坏的 pdf 的视图:

def DownloadPdf(request):

filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response

那么,我必须做些什么才能让它工作呢?

【问题讨论】:

标签: python django


【解决方案1】:
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
    response = HttpResponse(fh.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
    return response

【讨论】:

  • 这会将整个内容读入内存,最好使用 FileResponse 或让网络服务器处理发送。
  • @RemcoGerlich 是的,你是对的,但我认为 Vaios Lk 必须首先理解简单的事情。
【解决方案2】:

@Sergey Gornostaev 的代码工作完美,但我在我的代码下方发布,因为它是一种不同的方法。

我更正了一点我的代码:

def DownloadPdf(request):
    path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
    f = open(path_to_file, 'r')
    myfile = File(f)
    response = HttpResponse(myfile, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=filename'
    return response

但只有在 pdf 文件中(适用于 txt 文件)给我这个错误:

'utf-8' 编解码器无法解码位置 10 中的字节 0xe2

【讨论】:

  • 因为您以文本形式打开文件,但 pdf 是二进制文件。将 open 中的 'r' 更改为 'rb'。
  • 也可以!帮助我理解这一切。 thnx 人。
猜你喜欢
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多