你可以使用Python内置的文件操作函数将返回数据写入文件,然后使用HttpResponse返回下载链接和文件大小。

以下是一个示例代码:

import os
from django.http import HttpResponse

def download_file(request):
    # 获取返回数据
    data = '这是要写入文件的数据'
    
    # 将数据写入文件
    filename = 'test.txt'
    with open(filename, 'w') as f:
        f.write(data)
    
    # 获取文件大小
    file_size = os.path.getsize(filename)
    
    # 构造HttpResponse对象
    response = HttpResponse(open(filename, 'rb').read(), content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
    response['Content-Length'] = file_size
    
    # 删除临时文件
    os.remove(filename)
    
    return response

这个视图函数会将数据写入文件test.txt,然后构造一个HttpResponse对象,将文件作为二进制流返回给前端,同时设置Content-Disposition和Content-Length头,以提示浏览器下载该文件。最后,删除临时文件

python django 如何将返回数据 写成文件 返回前端 下载 返回文件大小

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

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