Reputation: 196
I want to download the image using the URL. this is what I am trying, but facing error Failed - No file.
import React, { useState, useEffect } from 'react';
import Download from '../assets/download.png'
//More imports
export function Home(props) {
const [image, setIamge] = useState([]);
const [imageUrl, setImageUrl] = useState('');
//more states
//More functions
const handleDownload = (item) => {
//item.url = "https://unsplash.com/photos/yC-Yzbqy7PY"
setImageUrl(item.url)
}
return (
<div className="home-container">
{
image.length ? image.map((item, key) => (
<div key={key} className="image-wrapper">
<Link className='download-link' to={imageUrl} target="_blank" download>
<img src={Download} onClick={() => { handleDownload(item) }} alt="fff" height="15px" width="15px" />
</Link>
</div>
)) : null}
</div>
);
}
export default Home;
I wanted to download the image on click of the download icon.
Upvotes: 0
Views: 1240
Reputation: 196
I tried this way and this is working fine for me.
import React, { useState, useEffect } from 'react';
import Download from '../assets/download.png'
//More imports
export function Home(props) {
const [image, setIamge] = useState([]);
const [imageUrl, setImageUrl] = useState('');
//more states
//More functions
const handleDownload = (item) => {
let a = document.createElement('a');
a.href = item.url + "/download?force=true";
a.download = 'image.png';
a.click();
}
return (
<div className="home-container">
{
image.length ? image.map((item, key) => (
<div key={key} className="image-wrapper">
<Link className='download-link' download>
<img src={Download} onClick={() => { handleDownload(item) }} alt="fff" height="15px" width="15px" />
</Link>
</div>
)) : null}
</div>
);
}
export default Home;
Upvotes: 1
Reputation: 1485
You can just directly open the link using like below and image will get downloaded. If you are framing your URL correctly, then you may try the below code for download
const handleDownload = (item) => {
//item.url = ""https://unsplash.com/photos/yC-Yzbqy7PY""
window.open(item.url, "_blank");
setImageUrl(item.url)
}
Upvotes: 0