gpt4 book ai didi

javascript - Django:从 View 返回文件后不开始下载

转载 作者:行者123 更新时间:2023-11-30 14:03:30 28 4
gpt4 key购买 nike

从各种 Stack Overflow 线程收集信息后,我在 Django 中想出了以下 View 函数,通过 HttpResponse 对象返回一个文本文件:

def serve_file(request):
filepath = sampler_settings.ZIP_PATH + '/test_file'
f = open(filepath, 'r')
response = HttpResponse(f, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="test_file"'
return response

函数是这样从前端调用的:

function serve_file() {
let url = 'http://127.0.0.1:8000/serve_file'
fetch(url)
.then(response => response.text())
.then(text => console.log(text))
}

然而,唯一发生的事情是文件内容打印在浏览器控制台中,但下载没有开始:没有提示或任何东西。

这是在 Ubuntu 和 Firefox 上的开发服务器上。

可能是什么原因?

最佳答案

原因是通过 ajax 的 http 请求与来自浏览器的正常请求不同。 Ajax 为您提供 JavaScript 响应。因此,您必须从浏览器(使用 window.location)本地请求文件,或者像这样通过 JavaScript 下载。

function serve_file() {
let url = 'http://127.0.0.1:8000/serve_file'
fetch(url)
.then(response => response.text())
.then(text => {

const blob = new Blob(text, {type: 'application/forced-download'});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "file_name";
document.body.appendChild(link);
link.click();
})
}

关于javascript - Django:从 View 返回文件后不开始下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882650/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com