ajax请求无法下载文件的原因


原因:

Ajax下载文件的这种方式本来就是禁止的。出于安全因素的考虑,javascript是不能够保存文件到本地的,

所以ajax考虑到了这点,只是接受json,text,html,xml格式的返回值,二进制的返回格式就会抛出这个异常。

因为response原因,一般请求浏览器是会处理服务器输出的response,例如生成png、文件下载等,

然而ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。

文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的,说白点就是js无法调用到浏览器的下载处理机制和程序。

解决方法:

1、用window.open() 或 window.location.href():

2、可以直接使用a标签实现文件下载:

<a href=”下载地址”>点击下载</a>

 var aLink = document.createElement('a'); aLink.download = "文件名"; aLink.href = "文件url地址"; document.body.appendChild(aLink); aLink.click(); document.body.removeChild(aLink);

3、可以使用jquery创建表单并提交实现文件下载:

var form = $("<form>"); form.attr("style","display:none"); form.attr("target",""); form.attr("method","post"); form.attr("action",rootPath + "T_academic_essay/DownloadZipFile.do"); var input1 = $("<input>"); input1.attr("type","hidden"); input1.attr("name","strZipPath"); input1.attr("value",strZipPath); $("body").append(form); form.append(input1); form.submit(); form.remove();

4、使用隐藏iframe或新窗体解决:

export const downloadFile = (url) => { const iframe = document.createElement("iframe"); iframe.style.display = "none"; // 防止影响页面 iframe.style.height = 0; // 防止影响页面 iframe.src = url; document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求 // 5分钟之后删除(onload方法对于下载链接不起作用,就先抠脚一下吧) setTimeout(()=>{ iframe.remove(); }, 5 * 60 * 1000); }

这个可以实现一次下载多个文件。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM