Unable to download a file from S3 by the URL in a browser

前提是你 提交于 2021-02-19 02:09:47

问题


I have such code snippet that used to be work with the previous versions of Google Chrome, but now it does not work. When I run this script I redirected to the page with the content of the file(it's a text) and with AWS URL(the same as in setAttribute).

var element = document.createElement('a');
element.setAttribute('href', 'https://s3-us-east-1.amazonaws.com/XXX/XXX/XXX?Signature=XXX&Expires=XXX&AWSAccessKeyId=XXX');
element.setAttribute('download', 'filename.txt');
document.body.appendChild(element);
element.click();

How to download this file?


回答1:


I made an error in the comments. Chrome still favours download attribute, but it completely ignores it if the anchor element has cross origin attributes ( meaning, if the file is hosted on a different domain).

To be able to download it, file needs to be served with header: Content-Disposition: attachment;

Check this tutorial to see how to set Content-Disposition in s3 management console: http://iwantmyreal.name/s3-download-only-presigned-upload




回答2:


Here is my solution:

    let downloadImage = url => {
      let urlArray = url.split("/")
      let bucket = urlArray[3]
      let key = `${urlArray[4]}/${urlArray[5]}`
      let s3 = new AWS.S3({ params: { Bucket: bucket }})
      let params = {Bucket: bucket, Key: key}
      s3.getObject(params, (err, data) => {
        let blob=new Blob([data.Body], {type: data.ContentType});
        let link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download=url;
        link.click();
      })
    }

The url parameter refers to the full url of the image.



来源:https://stackoverflow.com/questions/50151062/unable-to-download-a-file-from-s3-by-the-url-in-a-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!