-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
89 lines (76 loc) · 2.02 KB
/
index.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import express from "express";
import path from "path";
import fs from "fs";
import fileUpload from "express-fileupload";
import cors from "cors";
import bodyParser from "body-parser";
import morgan from "morgan";
import _ from "lodash";
const host = "localhost";
const port = 8080;
const app = express();
// enable files upload
app.use(
fileUpload({
createParentPath: true,
})
);
//add other middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("dev"));
app.listen(8080, () =>
console.log(`Server listening on http://${host}:${port}`)
);
app.use(express.static(path.join(__dirname, "static")));
app.post("/upload-file", async (req, res) => {
try {
if (!req.files) {
res.send({
status: false,
message: "No file uploaded",
});
} else {
//Use the name of the input field (i.e. "file") to retrieve the uploaded file
let file: any = req.files.file;
let fileName = await determinePath(file.name);
//Use the mv() method to place the file in upload directory (i.e. "uploads")
file.mv("./static/uploads/" + fileName);
//send response
res.send({
status: true,
message: "File is uploaded",
data: {
name: file.name,
mimetype: file.mimetype,
size: file.size,
fileUrl: `http://${host}:${port}/uploads/${fileName}`,
},
});
}
} catch (err) {
res.status(500).send(err);
}
});
async function determinePath(name: string) {
let resultingFileName = name;
let count = 1;
while (await fileExists(resultingFileName)) {
let pointIndex = name.lastIndexOf(".");
resultingFileName = `${name.slice(0, pointIndex)} (${count++})${name.slice(
pointIndex
)}`;
}
return resultingFileName;
}
async function fileExists(fileName: string) {
try {
let stats = await fs.promises.stat(
path.join(__dirname, "static", "uploads", fileName)
);
return true;
} catch (e) {
return false;
}
}