0

I am trying to download an image on click and using "download" attribute of HTML5 for this. this image has been uploaded by mobile app in s3 bucket. But it is redirecting the user to a new tab instead of downloading the image.I want to download this image directly.

<a href="<link>" download="file.jpg" target="_blank">Download image</a>

how can I solve this..? thanks in advance

  • https://stackoverflow.com/questions/49474775/chrome-65-blocks-cross-origin-a-download-client-side-workaround-to-force-down – CBroe Nov 20 '20 at 11:58

1 Answers1

0

Try this code :

function forceDownload(blob, filename) {
 var a = document.createElement('a');
  a.download = filename;
  a.href = blob;
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// Current blob size limit is around 500MB for browsers
function downloadResource(url, filename) {
  if (!filename) filename = url.split('\\').pop().split('/').pop();
  fetch(url, {
      headers: new Headers({
        'Origin': location.origin
      }),
      mode: 'cors'
    })
    .then(response => response.blob())
    .then(blob => {
      let blobUrl = window.URL.createObjectURL(blob);
      forceDownload(blobUrl, filename);
    })
    .catch(e => console.error(e));
}

downloadResource('https://pixxort-prod.s3.amazonaws.com/records/c6e6d1617041434da83ab5b959278fc41604921530373.jpg');

It will force browser to download resource from web.

Mayur Kukadiya
  • 2,461
  • 1
  • 25
  • 58