在django视图中下载文件时禁止访问

时间:2012-11-30 05:25:36

标签: python django

我有这段代码

class DownloadView(TemplateView):
    template_name = 'pdfform/create_form2.html'


    def serve_pdf(self, request):
        #pdf_data = magically_create_pdf()

        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="http://localhost/static/pdfs/angular.pdf"'
        return response

当我进入该页面时,我得到了下载对话框,但我无法下载该文件。它说那个

http 403 forbidden

现在我可以直接访问该文件,但将http://localhost/static/pdfs/angular.pdf放在浏览器中

我犯了static/pdfs/angular.pdf但同样的错误

1 个答案:

答案 0 :(得分:0)

Filename in应该只是一个纯文件名,而不是http://...

所以改变

response['Content-Disposition'] = 'attachment; filename="http://localhost/static/pdfs/angular.pdf"'

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

此外,您需要通过响应提供文件内容,以便提供文件内容。

e.g

...
def serve_pdf(self, request):
  from django.core.servers.basehttp import FileWrapper
  # your code

  wrapper      = FileWrapper(open(your_pdf_file_path))
  response     = HttpResponse(wrapper,'application/pdf')
  response['Content-Length']      = os.path.getsize(your_pdf_file_path)    
  response['Content-Disposition'] = 'attachment; filename="angular.pdf"'
  return response