简体   繁体   English

使用Javascript函数启动下载

[英]Initiate downloads with a Javascript function

I have multiple URLs for users to download. 我有多个URL供用户下载。 The download should be triggered after they hit "Like" or post a "Tweet". 他们点击“赞”或发布“推文”后,应触发下载。 I have successfully setup the callback functions for both. 我已经成功设置了两个的回调函数。

I wish to know how do I employ Javascript so that the multiple downloads are triggered simultaneously. 我想知道如何使用Javascript,以便同时触发多个下载。 One solution would be to use window.location , but that would trigger just single download. 一种解决方案是使用window.location ,但这将仅触发一次下载。 I can even do multiple window.open but the pop-up blocker would block this. 我什至可以做多个window.open但是弹出窗口阻止程序会阻止它。

What other alternatives do I have for this situation? 在这种情况下,我还有什么其他选择?

You can use this function if you need to make the browser download files without using content-disposition: attachment;filename=filename header. 如果需要使浏览器下载文件而不使用content-disposition: attachment;filename=filename标头,则可以使用此功能。

function aDownload( url, name ) {
    // Original code from https://github.com/eligrey/FileSaver.js
    // Rewrited to work without blobs
    // Will return true if worked
    var click, save_link, event;
    save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
    if( !("download" in save_link) ) return false; // a[download] not supported on this browser
    save_link.href = url;
    save_link.download = name;
    event = document.createEvent("MouseEvents");
    event.initMouseEvent(
        "click", true, false, window, 0, 0, 0, 0, 0
        , false, false, false, false, 0, null
    );
    return save_link.dispatchEvent(event); // false if event was cancelled
}

What you can do is create a hidden iframe with the src of the file for each download, something like: 您可以做的是为每次下载使用文件的src创建一个隐藏的iframe,例如:

function download(url){ 
  var iframe = document.createElement("iframe"); 
  iframe.src = url;
  iframe.style.display = "none"; 
  document.body.appendChild(iframe); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM