Hey guys Im trying to upload a file to s3 I am successfully able to do it with the following code. However I would like to make it a little more reusable. I would like to be able to use a function like this.
singleFileUpload(fieldName, bucketName, newfileName);
So that I an use the same function on multiple pages without defining it over and over again. I also want it to be able to return any upload errors in a try catch block. Is this possible? Heres the code I have so far that works.
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);
}
});
Any help here would be fantastic thank you.