1
votes

I am getting image url from response of a api i have created a component where i pass image url throught prop and then added in src of anchor tag now what i want is when user click on image image should be get downloaded but it is opening in new tab

const App = () =>{

const [pictureData, setPictureData] = useState({});

const [date,setDate] = useState("");

const inputValue = useRef(null)



const url= "https://api.nasa.gov/planetary/apod"

const fetchData = async (fetdate) =>{
    const {data} = await Axios.get(url,{
          params:{
              api_key: "keyhere",
              date : fetdate
          }
    })

    console.log(data.copyright);

    setPictureData(data)
}

useEffect( () =>{
     fetchData()
},[])

useEffect( ()=>{
     fetchData(date)
},[date])

const submitDate = (e) =>{
      e.preventDefault()
      console.log(inputValue.current.value);
      setDate(inputValue.current.value)
      console.log(date);
}

return(
  <div>
       <form onSubmit={submitDate}>
         <input type="text" name="date" ref={inputValue}/>
         <input type="submit"/>
       </form>
     <Card data={pictureData}/>
     <DownloadButton data={pictureData} />
  </div>
 
)

}

card.js:-

const Card = ({data}) =>{ return( <img src={data.hdurl} style={{width: "200px",height: "200px"}} alt=""/>

{data.copyright}

    )

}

DownloadButton.js :-

const DownloadButton = ({data}) =>{

return(
    <a href={data.hdurl} download>download</a>
)

}

1

1 Answers

0
votes

IE does not support download attribute in a. More modern browser support it, such as chrome.

But there is a method msSaveBlob in ie11, you can use it to force download the image in ie.

On the other hand, If you can control the remote server, Add Content-disposition", "attachment; filename=XXX.jpg to the response header will cause the browser to download the file instead of open it. You can use a query parameter to control this behaviour.