-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.js
43 lines (40 loc) · 1.19 KB
/
s3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const aws = require("aws-sdk");
const fs = require("fs");
let secrets;
if (process.env.NODE_ENV == "production") {
secrets = process.env; // in prod the secrets are environment variables
} else {
secrets = require("./secrets"); // in dev they are in secrets.json which is listed in .gitignore
}
const s3 = new aws.S3({
accessKeyId: secrets.AWS_KEY,
secretAccessKey: secrets.AWS_SECRET
});
// ---------------------
exports.upload = (req, res, next) => {
if (!req.file) {
console.log(`req.file ain't there`);
return res.sendStatus(500);
}
const { filename, mimetype, size, path } = req.file;
s3.putObject({
Bucket: "ninas-imageboard",
ACL: "public-read",
Key: filename,
Body: fs.createReadStream(path),
ContentType: mimetype,
ContentLength: size
}).promise().then(
() => {
// console.log('it worked!');
next();
// will delete file from upload folder(in our server), as soon as it is uploaded on AWS:
fs.unlink(path, () => {});
}
).catch(
err => {
console.log(err, 'failure :-(');
res.sendStatus(500);
}
);
};