[英]Download image (I have the link) from the front-end as user?
I want to allow my user to download a image, i know that if i have a file i can use the tag download and it will work, but it doesn't work if i have the link我想允许我的用户下载图像,我知道如果我有一个文件,我可以使用标签下载并且它会起作用,但是如果我有链接它就不起作用
I have already tried the download tag, and read the google cloud storage downloading-objects docs but the problem with the last one is that it gets downloaded on my server, also i tried to return the file but it is just a promise with no file info我已经尝试过下载标签,并阅读了谷歌云存储下载对象文档,但最后一个的问题是它被下载到我的服务器上,我也试图返回文件,但它只是一个没有文件的承诺信息
Front-end with the download code (doesn't work), i have tried it with download={preview}
带下载代码的前端(不起作用),我用download={preview}
试过了
<div className={classes.fileInputs}>
<a download href={preview} title="Imagen">
<img
src={preview}
alt='Preview obj'
className={classes.imgPreview}
/>
</a>
This is how i thought it should work but it didn't, download triggers a request to the back-end but the image is downloaded in my server这就是我认为它应该工作的方式,但它没有,下载会触发对后端的请求,但图像已下载到我的服务器中
<Button color="inherit" onClick={() => download()}>
Download
</Button>
I just want that a click in the button download will make the client have its image我只希望单击下载按钮将使客户端拥有其图像
If you want you can use axios:如果你愿意,你可以使用 axios:
axios({
url: 'http://localhost:5000/static/example.jpg',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.jpg');
document.body.appendChild(link);
link.click();
});
To set type of file and filename from "content-disposition" -header you can use this:要从 "content-disposition" -header 设置文件类型和文件名,您可以使用:
const blob = new Blob([response.data], {type: response.data.type}); const blob = new Blob([response.data], {type: response.data.type});
const url = window.URL.createObjectURL(blob); const url = window.URL.createObjectURL(blob);
const link = document.createElement('a'); const link = document.createElement('a');
link.href = url;链接.href = url;
const contentDisposition = response.headers['content-disposition']; const contentDisposition = response.headers['content-disposition'];
let fileName = 'unknown';让文件名 = '未知';
if (contentDisposition) {如果(内容处置){
const fileNameMatch = contentDisposition.match(/filename="(.+)"/);
if (fileNameMatch.length === 2)
fileName = fileNameMatch[1];
} }
link.setAttribute('download', fileName); link.setAttribute('下载', 文件名);
document.body.appendChild(link); document.body.appendChild(link);
link.click();链接。点击();
link.remove();链接.remove();
window.URL.revokeObjectURL(url); window.URL.revokeObjectURL(url);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.