可以使用HttpResponse对象的content_type参数来指定下载文件的MIME类型,使用HttpResponse对象的content-Disposition参数来指定下载文件的名称和保存方式。

例如,以下代码实现将文件以下载形式返回:

from django.http import HttpResponse
from django.shortcuts import render

def download_file(request):
    # 读取文件内容
    with open('path/to/file', 'rb') as f:
        file_data = f.read()
    # 构造HttpResponse对象
    response = HttpResponse(file_data, content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename="filename.txt"'
    return response

在上述代码中,content_type参数被设置为application/octet-stream,这是一种通用的二进制文件MIME类型。Content-Disposition参数被设置为attachment; filename="filename.txt",这表示浏览器应该将此文件保存为“filename.txt”并弹出“另存为”对话框

django 实现 返回的数据以下载文件形式返回

原文地址: https://www.cveoy.top/t/topic/fJAd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录