代码之家  ›  专栏  ›  技术社区  ›  Gabriel Ben Compte

下载文件并在响应中重定向

  •  0
  • Gabriel Ben Compte  · 技术社区  · 6 年前

    我想做出一个响应,既重定向到某个url,又不加载文件。要下载我使用的文件:

        content = "Example content"
        filename = "example-file-name".
        response = HttpResponse(content=content,
                                        content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
        return response
    

    要重定向到URL,请执行以下操作:

     response = HttpResponseRedirect(redirect_to=example_url)
    

    有没有一种方法可以在一个响应中同时做出这两件事?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vinay P    6 年前

    使用ajax可能是一个解决方案,通过ajax下载文件,然后在下载完成后启动重定向。

    ajax下载可以使用jquery或相关插件 post 供参考。

    重定向可以在客户端成功实现,如下所示。

     $.fileDownload('some/file.pdf')
        .done(function () { window.location.href = 'REDIRECT_URL'; })
        .fail(function () { alert('File download failed!'); });