首页 > 解决方案 > 下载文件并在响应中重定向

问题描述

我想做出一个既重定向到某个 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

重定向到网址:

 response = HttpResponseRedirect(redirect_to=example_url)

有没有办法在一个单一的回应中做出这两件事?

标签: pythondjango

解决方案


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

使用 JQuery 或相关插件可以轻松下载 AJAX,发帖供参考。

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

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

推荐阅读