-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.js
61 lines (51 loc) · 1.62 KB
/
server.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const express = require("express");
const AWS = require("aws-sdk");
const awsConfig = require("./config-aws");
const uuid = require("uuid");
const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Listening at port ${PORT}`));
AWS.config.update({ region: awsConfig.region });
const S3_BUCKET = awsConfig.bucketName;
const s3 = new AWS.S3({
accessKeyId: awsConfig.accessKeyId,
secretAccessKey: awsConfig.secretAccessKey,
region: awsConfig.region,
signatureVersion: "v4",
// useAccelerateEndpoint: true
});
const getPresignedUrl = (req, res) => {
let fileType = req.body.fileType;
if (fileType != ".jpg" && fileType != ".png" && fileType != ".jpeg") {
return res
.status(403)
.json({ success: false, message: "Image format invalid" });
}
fileType = fileType.substring(1, fileType.length);
const fileName = uuid.v4();
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName + "." + fileType,
Expires: 60 * 60,
ContentType: "image/" + fileType,
ACL: "public-read",
};
s3.getSignedUrl("putObject", s3Params, (err, data) => {
if (err) {
console.log(err);
return res.end();
}
const returnData = {
success: true,
message: "Url generated",
uploadUrl: data,
downloadUrl:
`https://${S3_BUCKET}.s3.amazonaws.com/${fileName}` + "." + fileType,
};
return res.status(201).json(returnData);
});
};
app.post("/generatePresignedUrl", (req, res) => getPresignedUrl(req, res));