简体   繁体   中英

Download mobile app uploaded image forcefully in web from s3 bucket. It is opening in tab instead of downloading

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM