node.js - nodejs s3存储桶上传脚本可重用
问题描述
嘿伙计们,我正在尝试将文件上传到 s3,我可以使用以下代码成功地做到这一点。但是我想让它更可重用。我希望能够使用这样的功能。
singleFileUpload(fieldName, bucketName, newfileName);
这样我就可以在多个页面上使用相同的功能,而无需一遍又一遍地定义它。我还希望它能够在 try catch 块中返回任何上传错误。这可能吗?这是我到目前为止有效的代码。
var AWS = require("aws-sdk");
var multer = require("multer");
multerS3 = require("multer-s3");
var fs = require("fs");
AWS.config.credentials = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: "eu-west-1"
};
AWS.config.region = "eu-west-1";
var s3 = new AWS.S3();
var newFileName = "coolNewFileName";
const fileFilter = (req, file, cb) => {
var ext = file.originalname.split(".")[1];
console.log("ext", ext);
if (ext == "jpg" || ext == "mp4" || ext == "wmv") {
cb(null, true);
} else {
cb(new Error("invalid file format"), false);
}
};
var upload = multer({
fileFilter,
storage: multerS3({
s3,
bucket: process.env.BUCKET_NAME,
acl: "public-read",
metadata: function(req, file, cb) {
cb(null, { fieldName: "testing_meta_data!" });
},
key: function(req, file, cb) {
console.log(file);
let fileExtension = file.originalname.split(".")[1];
cb(null, newFileName + "." + fileExtension);
}
})
});
var singleUpload = upload.single("image");
singleUpload(req, res, function(err) {
if (err) {
data.error = true;
data.message = err.message;
console.log(data);
res.json(data);
} else {
// res.json({ imageurl: req.file.location });
data.fileUploadLocation = req.file.location;
console.log(data.fileUploadLocation);
}
});
这里的任何帮助都会非常感谢。
解决方案
你可以让你的代码更安全,里面有这条线。Aws-sdk 知道在哪里查找您的凭据。
消除:
Aws.config.credentials
堵塞
添加:
const credentials = new AWS.SharedIniFileCredentials({profile: 'name-of-profile'});
推荐阅读
- javascript - Chrome 扩展 javascript 注入
- javafx - JavaFX 中心文本
- python - 为什么 multiprocessing 运行,CPU 使用率下降到 0%,但结果从未发布?
- api - PagerDuty 分页
- amazon-web-services - 将多个子网分配给路由表 aws
- jupyter-notebook - 无法连接到 jupyter localhost
- excel - VBA 导入动态 URL
- python-3.x - 如何打印出二维列表中的每个索引,索引之间没有括号和空行?
- flutter - Flutter 可滚动列,具有扩展的子项并位于容器内
- ios - 升级mac os和升级xcode后如何运行`npm react-native run-ios`?