【Django】简单实现文件下载的两种方式
原创
©著作权归作者所有:来自51CTO博客作者mb612dbeae73d01的原创作品,请联系作者获取转载授权,否则将追究法律责任
【Django】简单实现文件下载的两种方式
前端将文件id传到后端即可
【Django】后端url
path('file_download/<int:id>', views.file_download, name='file_download')
导入包
from wsgiref.util import FileWrapper
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse
from django.utils.encoding import
一.FileResponse
def file_download(request, id):
fileObj = ChangeRequestFile.objects.get(pk=id)
file_path = fileObj.file.file
file = open(str(file_path), 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote(fileObj.filename)
return
二.FileWrapper+FileResponse
def file_download(request, id):
file = ChangeRequestFile.objects.get(pk=id)
wrapper = FileWrapper(file.file.file)
content_type = 'application/octet-stream'
if file.suffix:
content_type = 'application/{}'.format(file.suffix)
response = FileResponse(wrapper, content_type=content_type)
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(
escape_uri_path(file.filename))
response['Access-Control-Expose-Headers'] = 'Content-Disposition'
return