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}
<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({
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();
});
You can check it in more details here
To set type of file and filename from "content-disposition" -header you can use this:
const blob = new Blob([response.data], {type: response.data.type});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
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);
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.