分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

js异步下载文件请求

发布时间:2023-09-06 02:33责任编辑:顾先生关键词:js

注意 :通常下载文件是用get请求

window.location.href=url;
但是 我们需要下载完成监听,所以必须要异步执行、用常规的ajax是不可以的。我们要用blob对象来实现
1.原生的如何实现
function loadDown(query) { ???????var url = "${ctx}/bill/billExport"+query; ???????var xhr = new XMLHttpRequest(); ???????xhr.open(‘GET‘, url, true);    // 也可以使用POST方式,根据接口 ???????xhr.responseType = "blob"; ???????xhr.onload = function () { ???????????if (this.status === 200) { ???????????????$(‘#loadingModal‘).modal(‘hide‘); ???????????????var content = this.response; ???????????????var aTag = document.createElement(‘a‘); ???????????????var blob = new Blob([content]); ???????????????var headerName = xhr.getResponseHeader("Content-disposition"); ???????????????var fileName = decodeURIComponent(headerName).substring(20); ???????????????aTag.download = fileName; ???????????????aTag.href = URL.createObjectURL(blob); ???????????????aTag.click(); ???????????????URL.revokeObjectURL(blob); ???????????} ???????}; ???????xhr.send() ???}
2 ajax如何实现
$.ajax({ ???????????url:options.url, ???????????// dataType:"text", ???????????// type:"get", ???????????success:function(result){ ???????????????var content = this.response; ???????????????var aTag = document.createElement(‘a‘); ???????????????var blob = new Blob([content]); ???????????????var headerName = xhr.getResponseHeader("Content-disposition"); ???????????????var fileName = decodeURIComponent(headerName).substring(20); ???????????????aTag.download = fileName; ???????????????aTag.href = URL.createObjectURL(blob); ???????????????aTag.click(); ???????????????URL.revokeObjectURL(blob); ???????????} ???????})

后台:

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));

参考博客:https://blog.csdn.net/Concsdn/article/details/79961295

https://blog.csdn.net/weixin_38661747/article/details/80754258

js异步下载文件请求

原文地址:https://www.cnblogs.com/coder-lzh/p/10435617.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved