Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...