python django 前端请求下载文件 后端 将数据以文件形式返回给前端
在Django中,可以使用HttpResponse对象将文件数据以文件形式返回给前端。具体步骤如下:
- 在视图函数中,获取文件数据并将其写入HttpResponse对象中:
def download_file(request):
# 获取文件数据
file_data = get_file_data()
# 将文件数据写入HttpResponse对象
response = HttpResponse(file_data, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename="example.txt"'
return response
其中,get_file_data()是获取文件数据的自定义函数,content_type指定返回数据的MIME类型,Content-Disposition设置为attachment用于告诉浏览器该文件是要下载的附件,filename指定下载后保存的文件名。
- 在前端发送GET请求,接收文件数据并将其保存为文件:
function downloadFile() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/download_file/');
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var blob = this.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'example.txt';
link.click();
}
};
xhr.send();
}
在请求中,设置responseType为blob用于接收二进制数据,通过创建a标签和设置href属性为生成的URL,再设置download属性为下载后保存的文件名,最后模拟点击a标签进行下载。
注意:由于生成的URL是临时的,需要在下载完成后释放资源,可以在下载完成后调用URL.revokeObjectURL()方法进行释放
原文地址: https://www.cveoy.top/t/topic/fI6r 著作权归作者所有。请勿转载和采集!