javascript - opening hidden iframe for file downlo

2019-02-20 03:50发布

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>

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?

1条回答
贪生不怕死
2楼-- · 2019-02-20 04:23

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');
});

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);
查看更多
登录 后发表回答