0

我有这个代码

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,但同样的错误

4

1 回答 1

1

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

所以改变

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

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

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

例如

...
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
于 2012-11-30T05:31:43.893 回答