javascript - 将响应与文件下载和重定向相结合
问题描述
我有一个视图,该 upn 调用,开始下载:
class PrintView(TemplateView):
template_name = "proj/listview.html"
def get(self, request, *args, **kwargs):
try:
filepath = TMP.IMG()
if os.path.exists(filepath):
with open(filepath, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/force-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(filepath)
messages.success(request, "image download started ...")
return response
messages.error(request, "something went wrong!")
return redirect("index")
except Exception as e:
messages.error(request, e)
return redirect("index")
在我的模板中,我调用了一个带有下载按钮的模式窗口,类似于:
<button id="dl_modal_submit" type="submit"</button>
上面有一些javascript:
let somvar = null;
$('#dlModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var modal = $(this);
});
document.querySelector('#dl_modal_submit').addEventListener('click', event => {
const params = {
somevar,
}
const paramStr = new URLSearchParams(params).toString();
const dl= `/dl/${somevar}`;
window.open(dl, "_self");
});
事情是,当我点击我想要的按钮时:
- 关闭模态
- 开始图片下载
- 重定向到索引
这里建议我使用两个视图来执行此操作,但肯定在 javascript 部分中必须有另一种方法来执行此操作?
解决方案
绝对地!
脚本.js:
$('#button').click(function() {
// close modal:
$('#modal').hide();
// download files:
window.open('the_download_url', '_blank');
// relocate:
window.location = 'the_redirect_url';
});
推荐阅读
- java - Java 执行查询返回 null
- spring-boot - 如何在 Spring Boot 中启用中途 TLS 连接
- embedded - 这个crc是如何正确计算的?
- javascript - Electron - 从 BrowserWindow 的 loadUrl() 中检索 HTTP 响应标头
- kubernetes - Openshift 4.2 - 无法连接到服务器:x509:证书已过期或尚未生效
- linux - 错误:-bash:tart:找不到命令...类似的命令是:'tar'
- windows - Nativescript Android 构建失败并带有标志 --env.compileSnapshot 在 Windows 上使用 Docker 工具箱
- python - 如何在 Windows 终端中设置 API_KEY?
- android - 用于两个不同对话框的对话框片段
- sql - 如何在 Oracle 中加入带有 UNION 结果的表?