fix: implement chunked file uploading to bypass proxy size limits
Build and Deploy / build-and-push (push) Successful in 27s
Build and Deploy / build-and-push (push) Successful in 27s
This commit is contained in:
@@ -216,6 +216,61 @@ app.post('/api/upload', authenticate, upload.single('file'), (req, res) => {
|
||||
res.json({ url });
|
||||
});
|
||||
|
||||
// 10b. Chunked Upload - Receive chunk
|
||||
app.post('/api/upload/chunk', authenticate, upload.single('file'), (req, res) => {
|
||||
const { uploadId, chunkIndex, totalChunks } = req.body;
|
||||
if (!req.file || !uploadId || !chunkIndex || !totalChunks) {
|
||||
return res.status(400).json({ error: 'Missing chunk data' });
|
||||
}
|
||||
|
||||
const tempDir = path.join(uploadsDir, 'temp', uploadId);
|
||||
if (!fs.existsSync(tempDir)) {
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
}
|
||||
|
||||
const chunkPath = path.join(tempDir, chunkIndex);
|
||||
fs.renameSync(req.file.path, chunkPath);
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// 10c. Chunked Upload - Complete
|
||||
app.post('/api/upload/complete', authenticate, (req, res) => {
|
||||
const { uploadId, fileName, totalChunks } = req.body;
|
||||
if (!uploadId || !fileName || !totalChunks) {
|
||||
return res.status(400).json({ error: 'Missing completion data' });
|
||||
}
|
||||
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
|
||||
const finalFileName = uniqueSuffix + '-' + fileName;
|
||||
const finalPath = path.join(uploadsDir, finalFileName);
|
||||
const tempDir = path.join(uploadsDir, 'temp', uploadId);
|
||||
|
||||
try {
|
||||
const writeStream = fs.createWriteStream(finalPath);
|
||||
for (let i = 0; i < totalChunks; i++) {
|
||||
const chunkPath = path.join(tempDir, i.toString());
|
||||
if (!fs.existsSync(chunkPath)) {
|
||||
throw new Error(`Chunk ${i} is missing`);
|
||||
}
|
||||
const data = fs.readFileSync(chunkPath);
|
||||
writeStream.write(data);
|
||||
}
|
||||
writeStream.end();
|
||||
|
||||
// Clean up temp dir
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
const url = `/uploads/${finalFileName}`;
|
||||
res.json({ url });
|
||||
} catch (error) {
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3005;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Backend server running on port ${PORT}`);
|
||||
|
||||
Reference in New Issue
Block a user