【问题标题】:Trouble downloading mp3 files from S3 using Amplify/Node使用 Amplify/Node 从 S3 下载 mp3 文件时遇到问题
【发布时间】:2020-01-07 05:27:51
【问题描述】:

我很困惑如何使用 Amplify 库来实际下载存储在我的 s3 存储桶中的 mp3 文件。我能够列出存储桶的内容并将其全部解析到树查看器中,供用户浏览各种文件,但是一旦我选择了一个文件,我就无法让它触发下载。

我确信我的放大配置是正确的,因为我可以看到所有预期的目录,并且当我选择要下载的文件时,我看到响应大小是正确的:

您可以看到它需要 2 多秒,并且似乎正在下载数据/mp3 文件,但从未提示用户保存文件,并且它不在我的下载文件夹中。

以下是从我的存储桶中捕获的文件元数据设置:

还有我调用的方法:

  getFile (fileKey) {
      Storage.get(fileKey, {download: true})
  }

如果没有“下载:true”配置,我会在响应中返回经过验证的 URL。如果可能,我想避免使用该 URL 下载文件进行第二次请求。还有什么我可能错过的吗? s3 操作回到标准的 aws-sdk 会更好吗?提前致谢!

【问题讨论】:

    标签: node.js vue.js amazon-s3 aws-amplify


    【解决方案1】:

    我最终使用了以下答案的组合: https://stackoverflow.com/a/36894564

    还有这个sn-p: https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

    因此文件在响应数据(结果)中被下载,我在文件中添加了更多元数据标签以获取文件名和标题。最后将链接添加到 DOM 并在其上执行 click() 以保存正确命名的文件。完整解决方案如下:

    getFile (fileKey) {
          Storage.get(fileKey, {download: true}).then(result => {
            console.log(result)
            let mimeType = result.ContentType
    
            let fileName = result.Metadata.filename
            if (mimeType !== 'audio/mp3') {
              throw new TypeError("Unexpected MIME Type")
            }
    
            try {
              let blob = new Blob([result.Body], {type: mimeType})
    
              //downloading the file depends on the browser
              //IE handles it differently than chrome/webkit
              if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(blob, fileName)
              } else {
                let objectUrl = URL.createObjectURL(blob);
                let link = document.createElement('a')
                link.href = objectUrl
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
              }
            } catch (exc) {
              console.log("Save Blob method failed with the following exception.");
              console.log(exc);
            }
    
          })
      }
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多