从 HTML 中的下载按钮下载由 API 生成的图像
Downloading image generated by API from download button in HTML
我有这个 QR 码生成器,它是我从网上的教程中拼凑而成的。你可以看到它here。它根据用户的输入用 Google API 生成的 QR 码替换 div 中的图像 src,所以这样做是行不通的,因为 link 是动态的。有没有办法通过按钮下载图片?
我不知道要附上代码的哪一部分才能说清楚,所以如果您想查看完整代码,请访问 GitHub 存储库:https://github.com/troop129/tarbiya/blob/main/index.html
感谢您的帮助!
不仅可以'download the image from a button',还可以在API响应后立即下载图片,然后从本地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>
我有这个 QR 码生成器,它是我从网上的教程中拼凑而成的。你可以看到它here。它根据用户的输入用 Google API 生成的 QR 码替换 div 中的图像 src,所以这样做是行不通的,因为 link 是动态的。有没有办法通过按钮下载图片?
我不知道要附上代码的哪一部分才能说清楚,所以如果您想查看完整代码,请访问 GitHub 存储库:https://github.com/troop129/tarbiya/blob/main/index.html
感谢您的帮助!
不仅可以'download the image from a button',还可以在API响应后立即下载图片,然后从本地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>