javascript - 打开隐藏的 iframe 以在文档准备好时下载文件

javascript - opening hidden iframe for file download on document ready(javascript - 打开隐藏的 iframe 以在文档准备好时下载文件)
本文介绍了javascript - 打开隐藏的 iframe 以在文档准备好时下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此技巧在文档准备就绪时打开文件下载对话框.同样的技巧对我来说又一次奏效了,但那次 iframe 是在 ajax 调用之后添加的.这是片段:

I’m trying to use this trick to open a file download dialog on document ready. The same trick has worked another time for me, but that time the iframe was added after an ajax call. This is the snippet:

<script type="text/javascript">
  $(document).ready(function() {
     var url='/my_file_url/';
     var _iframe_dl = $('<iframe />')
                       .attr('src', url)
                       .hide()
                       .appendTo('body');
  });
</script>

虽然 iframe 在 html 代码中正确打印,但它没有预期的行为:加载页面后没有出现下载文件弹出窗口.有什么帮助吗?

While the iframe is correctly printed in html code, it doesn’t have the expected behaviour: no download file popup appears after loading the page. Any help on why?

推荐答案

效果很好,假设 MIME 是一种将开始下载的类型,例如 application/octet-stream.由于内置 pdf 阅读器,您可能会遇到浏览器正在呈现它并且不提供下载的问题.

It works just fine, assuming that the MIME is of a type that will start a download, for example application/octet-stream. You may be encountering an issue where the browser is rendering it and not offering a download due to an in-built pdf reader.

$(document).ready(function(){
var url='data:application/octet-stream,hello%20world';
var _iframe_dl = $('<iframe />')
       .attr('src', url)
       .hide()
       .appendTo('body');
});

如果客户端在现代浏览器上,另一种解决方案是使用 <a> 并设置 hrefdownload,然后模拟点击它.

An alternate solution, if the client is on a modern browser, is to use an <a> with href and download set, then simulate a click on it.

var a = document.createElement('a'),
    ev = document.createEvent("MouseEvents");
a.href = url;
a.download = url.slice(url.lastIndexOf('/')+1);
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0,
                  false, false, false, false, 0, null);
a.dispatchEvent(ev);

这篇关于javascript - 打开隐藏的 iframe 以在文档准备好时下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)