-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
59 lines (49 loc) · 1.91 KB
/
main.js
File metadata and controls
59 lines (49 loc) · 1.91 KB
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
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
const UPLOAD_DIR = path.join(__dirname, "uploads");
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR);
app.get("/", (req, res) => {
res.sendFile(__dirname + '/index.html')
})
// Step 1: Create upload session
app.post("/create-upload", (req, res) => {
const uploadId = uuidv4();
const dir = path.join(UPLOAD_DIR, uploadId);
fs.mkdirSync(dir);
res.json({ uploadId, chunkSize: 1024 * 1024 }); // 1 MB chunks
});
// Step 2: Upload chunk
const storage = multer.memoryStorage();
const upload = multer({ storage });
app.post("/upload-chunk", upload.single("chunk"), (req, res) => {
const { uploadid, index } = req.body;
const chunkDir = path.join(UPLOAD_DIR, uploadid);
if (!fs.existsSync(chunkDir)) return res.status(400).send("Invalid uploadId");
const chunkPath = path.join(chunkDir, `chunk_${index}`);
fs.writeFileSync(chunkPath, req.file.buffer);
res.json({ status: "ok" });
});
// Step 3: Assemble chunks
app.post("/assemble", (req, res) => {
const { uploadid, totalChunks, filename } = req.body;
const chunkDir = path.join(UPLOAD_DIR, uploadid);
const finalPath = path.join(UPLOAD_DIR, filename);
const writeStream = fs.createWriteStream(finalPath);
for (let i = 0; i < totalChunks; i++) {
const chunkPath = path.join(chunkDir, `chunk_${i}`);
const data = fs.readFileSync(chunkPath);
writeStream.write(data);
fs.unlinkSync(chunkPath);
}
writeStream.end();
fs.rmdirSync(chunkDir);
res.json({ status: "done", path: finalPath });
});
app.listen(9090, () => console.log("Server running on http://localhost:9090"));