Search code examples
javascripthtmlimage

Directly download img tag


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

image.src = "http://skins.minecraft.net/MinecraftSkins/" + username + ".png";

Obviously this shows up in the document fine but I want the user to be able to save it to their local file system upon the click of a download button. I dynamically create an a tag, set the download attribute to the player username (and filetype, png), but I'm not sure what to set the href attribute to. Obviously, I could set it to the URL of the actual image tag, but unfortunately, this gives the downloaded file a very ugly and long name, which detracts from user experience. Since the image is cross-origin (and I cannot change this), I can't just plop it onto a canvas and convert it to raw data. But, still, I am sure there is some way to just let the user download from the image element, but I cannot find that way. (As if they right-click and hit "Save image as...")

I have tried setting the href attribute of the a object directly to the img tag, but the download fails due to "No file".

I have tried setting the href attribute to a newly-created Image object, but same error.

Note: Nothing can be done server-side.
For testing purposes, the username "ImAlgo" can be used


Solution

  • 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));