我尝试在同一窗口中下载图像,而不是要求最终用户在 react 中使用
。 save-image-as
或 Ctrl+S
。 js
以下函数是在 Stateful Class
中编写的。
forceDownload(event){
alert(event.target.getAttribute('value'));
var link = document.createElement('a');
link.download = 'Download.jpg';
document.body.appendChild(link);
link.href = event.target.getAttribute('value');
link.click();
}
以下代码写在render
部分
<a value={imageUrl} onClick={this.forceDownload}>Download</a>
仅当 alert
抛出 null
而不是实际的 imageUrl
时,该解决方案才能正常工作。有什么遗漏吗?
最佳答案
创建一个blob
并将其转换为可下载链接。
forceDownload(event){
const data = event.target.getAttribute('value');
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'quote.pdf');
document.body.appendChild(link);
link.click();
}
关于javascript - 如何使用 html/javascript 内联下载图像而不是 `save image as`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52421870/