javascript - Html:如何点击下载链接,而不是右键单击并另存为

标签 javascript html firefox

在我的 html 文件中,我希望在单击时有一个图像链接,它开始将图像下载到本地文件夹。一般要下载一个链接,我们必须右击然后选择另存为。

我尝试了以下方法:

 var href = document.createElement("a");
 href.setAttribute("href", url1);
 href.appendChild(document.createTextNode("Image Download"));
 href.setAttribute("download", "test.jpg");
 contentDiv.appendChild(href);

但是还是不行。我点击,图片在浏览器中打开

最佳答案

MDN Reference :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file. If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link (the user can change the name before actually saving the file of course). There are no restrictions on allowed values (though / and \ will be converted to underscores, preventing specific path hints), but you should consider that most file systems have limitations with regard to what punctuation is supported in file names, and browsers are likely to adjust file names accordingly.

Firefox 不支持 download 属性。

但是,如果您使用的是带有 JavaScript 的 Chrome,您可以尝试这样的操作:

var imageURL, contentDiv, href, img;
imageURL = "https://cdn3.iconfinder.com/data/icons/tango-icon-library/48/go-home-128.png";

contentDiv = document.getElementById("contentDiv");

href = document.createElement("a");
href.setAttribute("href", imageURL);
href.setAttribute("download", imageURL);

img = document.createElement("img");
img.alt = "Download image";
img.title = img.alt;
img.src = imageURL;

href.appendChild(img);
contentDiv.appendChild(href);
<div id="contentDiv"></div>

注意: 在 Google Chrome 中,您可以使用 download 属性,而无需设置要下载的 url。

例子:

<a href="https://cdn3.iconfinder.com/data/icons/tango-icon-library/48/go-home-128.png" download>Image Download</a>

关于javascript - Html:如何点击下载链接,而不是右键单击并另存为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677966/

相关文章:

html - 边框导致DIV溢出

jquery - 奇怪的内联样式来自哪里?

javascript - 我们如何让 momentJS 以 mm 为单位显示 60 分钟 :ss format?

javascript - AngularJS:$scope 与此:$scope 的用途是什么?

javascript - toggleClass 错误 - 使用 click 事件通过 jQuery Mobile 隐藏类?

javascript - CSS 中内嵌的 SVG 图像

javascript - 使用 Bootstrap 按钮组交换 Div

javascript - 使用 JavaScript 打开新浏览器窗口时出错

javascript - 火狐网络扩展 : selectionText in contextMenus only returns 150 characters

javascript - Firefox 中 JavaScript 文件的最大文件大小