Reputation: 81
I have this QR code generator that I pieced together from tutorials across the web. You can see it here. It replaces an image src in a div with the QR code generated from Google API based on input from the user, so doing doesn't work, as the link is dynamic. Is there a way to download the image from a button?
I didn't know what part of the code to attach to make it clear, so if you want to see the entire code, visit the GitHub repository: https://github.com/troop129/tarbiya/blob/main/index.html
Thanks for your help!
Upvotes: 1
Views: 969
Reputation: 3130
Not only it is possible to 'download the image from a button', but you can also download the image immediately after the API responds and then display it from a local URL.
const url = 'https://picsum.photos/200/300';
const target = document.getElementById('target');
const link = document.getElementById('download');
const xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', (e) => {
const blobUrl = URL.createObjectURL(e.target.response);
target.src = blobUrl;
link.href = blobUrl;
link.download = 'image.jpg';
});
xhr.responseType = 'blob';
xhr.open('GET', url);
xhr.send();
<img id='target'></img>
<a id='download'>Download</a>
Upvotes: 1