【发布时间】:2019-04-27 16:36:20
【问题描述】:
从各种 Stack Overflow 线程收集信息后,我在 Django 中提出了以下视图函数,通过 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 上的开发服务器上。
可能是什么原因?
【问题讨论】:
-
你试过
document.location = "http://127.0.0.1:8000/serve_file";吗? (如果要保存文件,需要让浏览器处理)
标签: javascript python ajax django