我想使我的项目目录中的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中运行。

最佳答案

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

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

10-07 13:50
查看更多