Directly download img tag

前端 未结 2 451
独厮守ぢ
独厮守ぢ 2021-01-29 05:45

I have an image tag which is cross-origin, and it\'s src is assigned dynamically.

image.src = \"http://skins.minecraft.net/MinecraftSkins/\" + usern         


        
相关标签:
2条回答
  • 2021-01-29 05:56

    You can use fetch(), YQL to get data URI representation of resource, <a> element and download attribute to set suggested file name for resource offered for download to user at each chromium and firefox.

    let username = "ImAlgo";
    
    let url = `http://skins.minecraft.net/MinecraftSkins/${username}.png`;
    
    let query = `https://query.yahooapis.com/v1/public/yql?q=select * from data.uri where url="${url}"&format=json&callback=`;
    
    let a = document.createElement("a");
    
    a.download = `${username}.png`;
    
    fetch(query).then(response => response.json())
    .then(({query:{results:{url}}}) => {
      a.href = url;
      document.body.appendChild(a);
      a.click();
    })
    .catch(err => console.log(err));

    0 讨论(0)
  • 2021-01-29 06:15

    In a download link, the download attribute is for the filename the user who downloads the file sees, the href is for the link to the image ex.:

    <a href="/images/coolimage3424623.png" download="skin.png">
    
    0 讨论(0)
提交回复
热议问题