首页 > 解决方案 > 上传到amazon aws s3时如何获取本地文件?

问题描述

这是我在网上找到的解决方案:[ https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html]

function addPhoto(albumName) {
  var files = document.getElementById('photoupload').files;
  if (!files.length) {
    return console.log('Please choose a file to upload first.');
  }
  var file = files[0];
  var fileName = file.name;
  var albumPhotosKey = encodeURIComponent(albumName) + '//';

  var photoKey = albumPhotosKey + fileName;
  s3.upload({
    Key: photoKey,
    Body: file,
    ACL: 'public-read'
  }, function(err, data) {
    if (err) {
      return console.log('There was an error uploading your photo: ', err.message);
    }
    console.log('Successfully uploaded photo.');
    viewAlbum(albumName);
  });
}

但是,在我目前的环境中,没有所谓的“文档”这个概念。我真的不知道“文档”是如何工作的。我可以在当前环境中包含“文档”吗?或者我可以使用其他东西来获取本地文件[图像]?非常感谢!

s3.upload:https ://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

标签: amazon-web-servicesamazon-s3

解决方案


您应该指定您的环境是什么。document对象仅在 HTML 中有意义,HTML 是在浏览器中运行的网页。如果您不是在浏览器中运行而是独立运行,您可能会使用 Node.js。

文档所述,Body参数可以是 Buffer、Typed Array、Blob、String 或 ReadableStream。

因此,在 Node.js 中简单上传本地文件可能如下所示:

var fs = require('fs');
var stream = fs.createReadStream('/my/file');

s3.upload({
   Bucket: 'mybucket',
   Key: 'myfile'
   Body: stream
}, function(err, data) {
   if (err) return console.log('Error by uploading.', err.message);
   console.log('Successfully uploaded.');
});

推荐阅读