【问题标题】:Django: download does not start after returnig a file from viewDjango:从视图返回文件后下载不开始
【发布时间】: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


【解决方案1】:

原因是通过 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();
    })
}

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多