【问题标题】:how to prompt user to save a pdf file to his local machine in django?如何提示用户将 pdf 文件保存到 django 中的本地计算机?
【发布时间】:2020-10-23 17:36:05
【问题描述】:

我对 Django 很陌生,我的项目要求我在点击链接时提示用户打开 pdf。我的本地机器上已经有 pdf 文件,不想使用 Reportlab 重新创建它。有什么办法吗?

我试过了

with open("/user/some/directory/somefilename.pdf") as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
        return response

但它返回 404 page not found 因为请求的 url 不在 myproject.urls 的 URLconf 中

我错过了什么?

【问题讨论】:

    标签: django pdf-generation reportlab


    【解决方案1】:

    对我有用的方法是使用 FileSystemStorage

    from django.core.files.storage import FileSystemStorage
    from django.http import HttpResponse
    
    fs = FileSystemStorage("/Users/location/where/file/is_saved/")      
    with fs.open("somefile.pdf") as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="my_pdf.pdf"'
        return response
    

    现在它提示用户像往常一样保存文件!

    【讨论】:

      【解决方案2】:

      一般来说,当用户点击“下载”时,您可以:

      - If file is not existed:
          - Generate pdf file use ReportLab as you did.
          - Store generated file to a public dir.
      return HttpResponseRedirect(file_url_to_public_dir)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 2020-09-08
        相关资源
        最近更新 更多