amazon-web-services - 是否可以使用 POST 直接从 URL 上传到 S3?

标签 amazon-web-services amazon-s3

我知道有一种方法可以使用 POST 直接从 Web 浏览器上传到 S3,而无需将文件发送到后端服务器。但是有没有办法从 URL 而不是网络浏览器做到这一点。

例如,上传位于 http://example.com/dude.jpg 的文件使用 post 直接到 S3。我的意思是我不想将 Assets 下载到我的服务器然后将其上传到 S3。我只想向 S3 发出 POST 请求,它会自动上传。

最佳答案

我想我应该分享我的代码来实现类似的东西。我在后端工作,但可能可以在前端做类似的事情,但要注意 AWS 凭证 可能是暴露 .

出于我的目的,我想从外部 URL 下载文件,然后最终取回上传文件的 URL 表单 S3。

我也用过 axios 为了获得可上传的格式和 file-type 获得正确类型的文件,但这不是要求。

以下是我的代码片段:

async function uploadAttachmentToS3(type, buffer) {
  var params = {
   //file name you can get from URL or in any other way, you could then pass it as parameter to the function for example if necessary
    Key : 'yourfolder/directory/filename', 
    Body : buffer,
    Bucket : BUCKET_NAME,
    ContentType : type,
    ACL: 'public-read' //becomes a public URL
  }
  //notice use of the upload function, not the putObject function
  return s3.upload(params).promise().then((response) => {
    return response.Location
  }, (err) => {
    return {type: 'error', err: err}
  })
}

async function downloadAttachment(url) {
  return axios.get(url, {
    responseType: 'arraybuffer'
  })
  .then(response => {
    const buffer = Buffer.from(response.data, 'base64');
    return (async () => {
      let type = (await FileType.fromBuffer(buffer)).mime
      return uploadAttachmentToS3(type, buffer)
    })();
  })
  .catch(err => {
    return {type: 'error', err: err}
  });  
}

let myS3Url = await downloadAttachment(url)

我希望它可以帮助那些仍在为类似问题而苦苦挣扎的人。祝你好运!

关于amazon-web-services - 是否可以使用 POST 直接从 URL 上传到 S3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586533/

相关文章:

amazon-s3 - 如何使 Plupload 直接上传到 Amazon S3?

browser - AWS S3 : Force File Download using 'response-content-disposition'

部署到 heroku 时 JavaScript 堆内存不足 - 针对 AWS S3 删除对象的 Nestjs 应用程序 API 请求

amazon-web-services - 如何在北京(中国)存储桶和全局存储桶之间同步 S3 中的数据?

python - boto aws 下拉实例列表

java - 用于创建 Lambda 的 AWS Java SDK 版本

amazon-web-services - SFTP Chroot 用户到挂载的 S3 存储桶

amazon-web-services - 使用 CORS 从 S3 删除文件

python - 使用 Zappa 部署 Flask 应用程序时出错

amazon-web-services - 做cloudformation打包时如何在s3中动态创建文件夹