python - 使文件可下载

时间:2012-08-06 14:33:52

标签: python django

我想将项目目录中的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>

urls.py:

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

views.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。

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:4)

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

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