0

I have trouble downloading an image when clicking on an image link. I'm prepending download?image= before the image url, it is giving the save option but fails to get downloaded.

Here is my code:

<a href={`download?image=${data[0].compress_path}`} download={(data[0].file_name).substring(data[0].file_name.lastIndexOf('/') + 1)} type="application/octet-stream" target="_blank">Download</a>

Note:Without using download?image= it is opening image in new tab.

Abhinav
  • 83
  • 1
  • 6
  • What do you mean "failed to get downloaded"? What happens? – Miguel Stevens Aug 19 '19 at 14:08
  • Prep-ending something that does not exist will give you the exact output it gives now. File should be web accessible, also "download" and "href" attributes need quotes. When you open in new page, image should display. – Mihai Iorga Aug 19 '19 at 14:11
  • 1
    take a look to this [question](https://stackoverflow.com/questions/49736214/force-a-download-to-download-image-instead-of-opening-url-link-to-image/49736875) – Azzabi Haythem Aug 19 '19 at 14:22

1 Answers1

0

My problem has been solved.I used File-saver.js library to download images. Here is the code :

<a  href='javascript:void(0)' onClick={()=>{this.download(data[0].compress_path)}} >Download</a>

And below is the download function which i have used:

    download=(save)=>{
        var FileSaver = require('file-saver');
        var fileName=save.substring(save.lastIndexOf('/') + 1)
        FileSaver.saveAs(save, fileName);
    }

Note:Use import { saveAs } from 'file-saver'to use saveAs.

Abhinav
  • 83
  • 1
  • 6