我是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页未找到,因为请求的url不在myproject.urls的URLconf中
我遗漏了什么?
发布于 2020-07-04 23:59:29
对我来说起作用的方式是使用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
现在它会提示用户像往常一样保存文件!
发布于 2020-07-03 03:22:43
一般情况下,当用户点击下载时,您可以:
- 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)
https://stackoverflow.com/questions/62707874
复制