python-making文件下载

2024-04-30 06:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使我的项目目录中的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中工作,但在ChromeV21.0中不工作。


Tags: topathpypdf链接responsedownloadline
2条回答

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

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

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

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

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

相关问题 更多 >