简体   繁体   English

Javascript:链接“单击”时自动下载文件

[英]Javascript: auto-download file when link “clicked”

I found a similar question, posted in an older topic, but the answer given there did not work. 我发现了一个类似的问题,该问题发布在一个较旧的主题中,但是在那里给出的答案无效。 I am testing with Mozilla Firefox browser (latest version). 我正在使用Mozilla Firefox浏览器(最新版本)进行测试。

I have an array with imageLinks, and want to auto-trigger a download without user interaction. 我有一个包含imageLinks的数组,并且想要在没有用户交互的情况下自动触发下载。 my code is given below: 我的代码如下:

for (var i=0; i<imageLinks.length; i++) {

if (imageLinks[i]) {

    console.log(imageLinks[i]);
    var link = document.createElement('a');
    link.href = imageLinks[i];
    link.download = 'imagefile';
    link.click();
    }
}

However, in Forefox the images are opening in new tabs? 但是,在Forefox中,图像是否在新标签页中打开?

I stumbled upon this snippet on a forum, and it seems to do the trick. 我在一个论坛上偶然发现了这个片段,这似乎可以解决问题。 Note however that the browser will still ask the user whether s/he wants the file(s) to be saved, and where. 但是请注意,浏览器仍会询问用户是否要保存文件以及保存位置。 This query can be accepted as "automatically do this with files of this type", and from then onwards the downloads will be automatically saved to the local drive. 该查询可以被接受为“使用此类型的文件自动执行此操作”,从那时起,下载内容将自动保存到本地驱动器中。

function simulateClick() {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    var a = document.getElementById('myLink');
    a.dispatchEvent(evt);
  }

This function can be called on the array with image links, and the user selected images can be saved to the drive. 可以在具有映像链接的阵列上调用此函数,并且用户选择的映像可以保存到驱动器。 I am happy with this solution, since it's easier to implement than a ZIP-file with user selected images. 我对这种解决方案感到满意,因为它比带有用户所选图像的ZIP文件更易于实现。 The image galleries are small, so the downloads should be initialized rather quick. 图像库很小,因此应该相当快地初始化下载。

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

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