在我的Django视图中,我创建了一个pdf文件,我想下载它。 该文件存在(路径:/app/data/4.pdf),我启动此命令:
Float32Array
但是下载没有启动且没有错误。你有解决方案吗? 感谢。
答案 0 :(得分:0)
试试这个,我用这行来下载文件
from django.http import HttpResponse
from wsgiref.util import FileWrapper
import os
def download(request, file_path):
"""
e.g.: file_path = '/tmp/file.pdf'
"""
try:
wrapper = FileWrapper(open(file_path, 'rb'))
response = HttpResponse(wrapper, content_type='application/force-download')
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
except Exception as e:
return None
答案 1 :(得分:0)
当文件已经存在时,我使用FileResponse进行文件下载。 FileResponse自Django 1.7.4起就存在。
from django.core.files.storage import FileSystemStorage
from django.http import FileResponse
def download_line(request):
fs = FileSystemStorage('/absolute/folder/name')
FileResponse(fs.open('filename.pdf', 'rb'), content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="filename.pdf"'
return response
答案 2 :(得分:0)
您可以通过链接和静态方式在应用程序中下载现有文件,例如
<a href="{% static 'questions/import_files/import_questions.xlsx' %}" download>Excel Format File </a>
答案 3 :(得分:-2)
def sample_download_client_excel(request):
"""
e.g.: file_path = '/tmp/file.pdf'
"""
try:
obj = SampleFile.objects.all().first()
file_path = obj.file_name.url.strip('/')
wrapper = FileWrapper(open(file_path, 'rb'))
response = HttpResponse(
wrapper,
content_type='application/force-download'
)
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
except Exception as e:
return None