简体   繁体   English

无法通过浏览器中的URL从S3下载文件

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

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). 当我运行此脚本时,我重定向到包含文件内容(它是文本)和AWS URL(与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? 如何下载此文件?

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). Chrome仍然支持下载属性,但如果锚元素具有跨源属性(意味着,如果文件托管在不同的域上),则它完全忽略它。

To be able to download it, file needs to be served with header: Content-Disposition: attachment; 为了能够下载它,需要使用标题提供文件: 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 查看本教程,了解如何在s3管理控制台中设置Content-Disposition: http//iwantmyreal.name/s3-download-only-presigned-upload

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. url参数指的是图像的完整URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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