【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