Django调用保存文件的函数不能工作



我正在创建Django项目并创建用于下载文件的函数,但是我的项目无法工作,文件不响应保存

view.py

from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
def index(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'my_file.json'
filepath = BASE_DIR + '/filedownload/' + filename
download(request,filepath)
return HttpResponse('Download File')
def download(request, path):
file_path = path
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/x-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404

我该如何解决这个问题?

您的download()返回对您的index()的响应并且index()返回它自己的响应(而不是download()的响应)。如果你像下面这样返回download()的响应,它将工作。

import os
from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
def index(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'my_file.json'
filepath = BASE_DIR + '/filedownload/' + filename
return download(request,filepath)
def download(request, path):
file_path = path
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/x-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404

最新更新