我目前使用如下方式将单个对象上传到 S3:
var options = {
Bucket: bucket,
Key: s3Path,
Body: body,
ACL: s3FilePermissions
};
S3.putObject(options,
function (err, data) {
//console.log(data);
});
但是,例如,当我有一个大型资源文件夹时,我使用 AWS CLI工具。
我想知道,有没有一种本地方法可以用 aws sdk 做同样的事情(将整个文件夹上传到 s3)?
最佳答案
老派递归方式我匆匆忙忙起来。仅使用核心 Node 模块和标准 AWS sdk。
var AWS = require('aws-sdk');
var path = require("path");
var fs = require('fs');
const uploadDir = function(s3Path, bucketName) {
let s3 = new AWS.S3();
function walkSync(currentDirPath, callback) {
fs.readdirSync(currentDirPath).forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walkSync(filePath, callback);
}
});
}
walkSync(s3Path, function(filePath, stat) {
let bucketPath = filePath.substring(s3Path.length+1);
let params = {Bucket: bucketName, Key: bucketPath, Body: fs.readFileSync(filePath) };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log('Successfully uploaded '+ bucketPath +' to ' + bucketName);
}
});
});
};
uploadDir("path to your folder", "your bucket name");
特别感谢 this post 的 Ali帮助获取文件名
关于javascript - 在 Node js 中使用 AWS sdk 将整个目录树上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27670051/