在我的 html 文件中,我希望在单击时有一个图像链接,它开始将图像下载到本地文件夹。一般要下载一个链接,我们必须右击然后选择另存为。
我尝试了以下方法:
var href = document.createElement("a");
href.setAttribute("href", url1);
href.appendChild(document.createTextNode("Image Download"));
href.setAttribute("download", "test.jpg");
contentDiv.appendChild(href);
但是还是不行。我点击,图片在浏览器中打开
最佳答案
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/