【问题标题】:How right download file from AWS S3 use JS从 AWS S3 下载文件如何正确使用 JS
【发布时间】:2021-01-14 16:50:37
【问题描述】:

我尝试从 AWS S3 下载文件,该文件下载成功,但它没有保存在我的磁盘中,并且我没有收到任何错误。

<script>
import AWS from 'aws-sdk';
import FS from 'browserify-fs';

export default {
  computed: {
    s3Client() {
      // Enter copied or downloaded access ID and secret key here
      const ID = 'RANDOM_ID';
      const SECRET = 'RANDOM_SECRET';

      return new AWS.S3({
        accessKeyId: ID,
        secretAccessKey: SECRET
      })
    }
  },
  methods: {
    downloadFile() {
      const BUCKET_NAME = 'js-bucket'
      const FILE_NAME = 'test.epub'

      const params = {
        Key: FILE_NAME,
        Bucket: BUCKET_NAME
      }

      console.info("Try to download file : " + FILE_NAME + " from bucket: " + BUCKET_NAME)

      this.isDownloading = true

      this.s3Client.getObject(params)
      .promise()
      .then(data => {

        FS.writeFile(FILE_NAME, data.Body, function (err) {
          if (err) {
            console.log(err.code, "-", err.message);
          }
        })

        console.log('File downloaded successfully')
      })
      .catch(err => console.error(err))
    }
  }
}

</script>

在控制台中,我看到有关成功保存的消息:文件已成功下载。但这是不对的。

【问题讨论】:

  • 您的代码中有&lt;script&gt; 标签,所以我假设您正在尝试从浏览器运行它?您的 S3 资源是否可公开访问?
  • browserify-fs 是 Node 的 fs 在 level.js 之上实现的,它是 indexeddb 的 leveldown 存储。您希望它将文件保存到您的计算机吗?
  • 是的,我期待它
  • 如果我使用默认库,我会看到相同的结果。

标签: javascript amazon-web-services amazon-s3


【解决方案1】:

我自己决定的:

  .promise()
  .then(data => {
    const blob = new Blob([data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = FILE_NAME
    link.click()
    URL.revokeObjectURL(link.href)

    console.log('File downloaded successfully')
  })

它有效,但如果有人知道如何做得更好,请回答。

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2021-06-26
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多