Django文件下载函数无法正常保存文件问题求助
Django文件下载功能修复方案
核心问题分析
你的代码存在三个关键问题:index函数未返回下载响应、download函数缩进错误、Content-Disposition参数未触发下载行为,此外还有导入和路径拼接的不规范问题。
分步修复
1. 修正index函数的响应返回
你调用了download生成下载响应,但未将其返回给客户端,而是返回了普通文本,导致下载请求被覆盖。修改后:
def index(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'my_file.json' # 用os.path.join避免路径分隔符问题 filepath = os.path.join(BASE_DIR, 'filedownload', filename) # 返回download生成的响应对象 return download(request, filepath)
2. 修复download函数的缩进错误
原代码中if语句下的with块未缩进,会触发Python语法错误,修正后:
def download(request, path): file_path = path if os.path.exists(file_path): # 缩进确保代码块属于if分支 with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/json") response['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' return response raise Http404
3. 修改Content-Disposition触发下载
原代码使用inline会让浏览器直接显示文件内容,改为attachment才会触发保存弹窗,同时用f-string给文件名加引号,避免特殊字符报错。
4. 统一优化导入
去掉重复导入,在文件顶部统一引入所需模块:
from django.http import HttpResponse, Http404 import os from django.conf import settings
完整修正代码
from django.http import HttpResponse, Http404 import os from django.conf import settings def index(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'my_file.json' filepath = os.path.join(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: # JSON文件使用对应content-type更规范 response = HttpResponse(fh.read(), content_type="application/json") response['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' return response raise Http404
内容的提问来源于stack exchange,提问作者MaTaDoRcpe
相关产品推荐
相关产品推荐

