一键下载按钮以获得gif图片 [英] One-click download button for a giphy gif
本文介绍了一键下载按钮以获得gif图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为图像创建一键式下载链接。我得到的html5下载属性结果不一致。
I want to create a one-click download link for images. I get inconsistent results with the html5 download attribute.
W3学校有一个触发下载的有效示例: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download
W3 schools has a working example triggering a download: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download
当我将图片网址更改为其他任何内容时,它不会不触发文件下载。
When I change the image urls to anything else it does not trigger a file download.
例如,此代码不t触发下载:
For example this code doesn't trigger a download:
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" download>
任何人都可以
推荐答案
我问了相同的问题下载,以下是对我有用的代码:
I asked the same question, here is the code that worked for me:
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();
这篇关于一键下载按钮以获得gif图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文