6

当用户单击链接时,我想在我的项目目录中制作一个可下载的 PDF 文件,而不是在浏览器中打开。

我按照这个问题Generating file to download with Django

但我收到错误:

Exception Type: SyntaxError
Exception Value: can't assign to literal (views.py, line 119)
Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module, line 35

我创建了一个下载链接:

 <a href="/files/pdf/resume.pdf" target="_blank" class="btn btn-success btn-download" id="download" >Download PDF</a>

网址.py:

url(r'^files/pdf/(?P<filename>\{w{40})/$', 'github.views.pdf_download'),

视图.py:

def pdf_download(request, filename):
    path = os.expanduser('~/files/pdf/')
    f = open(path+filename, "r")
    response = HttpResponse(FileWrapper(f), content_type='application/pdf')
    response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'
    f.close()
    return response

错误行是:

response = ['Content-Disposition'] = 'attachment; filename=resume.pdf'

我怎样才能使它可下载?

谢谢!

更新

它适用于 Firefox,但不适用于 Chrome v21.0。

4

2 回答 2

8

使用以下代码,它应该下载文件而不是在新页面中打开它

def pdf_download(request, filename):
  path = os.expanduser('~/files/pdf/')
  wrapper = FileWrapper(file(filename,'rb'))
  response = HttpResponse(wrapper, content_type=mimetypes.guess_type(filename)[0])
  response['Content-Length'] = os.path.getsize(filename)
  response['Content-Disposition'] = "attachment; filename=" + filename
  return response
于 2013-02-01T11:48:01.360 回答
5

=在该行中有一个额外的内容,这使得语法无效。它应该是

response['Content-Disposition'] = 'attachment; filename=resume.pdf'

(请注意,拥有两个=并不一定会使其无效:foo = bar = 'hello'完全有效,但在这种情况下,左侧和中间项都是名称。在您的版本中,中间项是文字,不能分配给它。 )

于 2012-08-06T14:35:11.220 回答