-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
64 lines (51 loc) · 1.82 KB
/
app.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
62
63
64
import express from "express";
import fileUpload from "express-fileupload";
import randomString from "random-base64-string";
import https from "https";
import http from "http";
import fs from "fs";
import dotenv from "dotenv";
dotenv.config();
let app = express();
const storagePath = process.env.STORAGE_PATH;
const stringLength = parseInt(process.env.STRING_LENGTH);
const cacheTtl = process.env.CACHT_TTL;
app.use("/u", express.static(storagePath, {maxAge: cacheTtl}));
app.use(fileUpload());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.post("/upload", async (req, res) => {
try {
if (!req.files) {
res.status(400).send("Error: No file provided");
return;
}
if (!req.files.image.mimetype.match(/image.*/)) {
res.status(400).send("Error: File not of type image");
return;
}
if (req.files.image.size > 50 * 1000 * 1000) {
res.status(400).send("Error: File too large, max. 50 MB allowed");
return;
}
let image = req.files.image;
let fileType = image.name.split(".").slice(-1)[0];
let randomName = randomString(stringLength);
let path = randomName + "." + fileType;
while (fs.existsSync(storagePath + path)) {
randomName = randomString(stringLength);
path = randomName + "." + fileType;
}
image.mv(storagePath + path);
res.send("/u/" + path);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
https.createServer({
key: fs.readFileSync(process.env.HTTPS_KEY_PATH),
cert: fs.readFileSync(process.env.HTTPS_CERT_PATH)
}, app).listen(process.env.PORT, () => console.log("Image Server now listening on port " + process.env.PORT));