Spaces:
Running
Running
const express = require('express'); | |
const { v4: uuidv4 } = require('uuid'); | |
const path = require('path'); | |
const fs = require('fs'); | |
const app = express(); | |
app.put('/:filename', (req, res) => { | |
const shortId = uuidv4().slice(0, 5); | |
const filename = req.params.filename; | |
const filepath = path.join(__dirname, `/uploads/${shortId}-${filename}`); | |
const fileStream = fs.createWriteStream(filepath); | |
req.pipe(fileStream); | |
req.on('end', () => { | |
const fileUrl = `http://localhost:7860/${shortId}/${filename}`; | |
res.send(`Uploaded file to ${fileUrl}`); | |
// Hapus file setelah 24 jam | |
setTimeout(() => { | |
fs.unlink(filepath, (err) => { | |
if (err) console.error(`Error deleting file: ${err}`); | |
}); | |
}, 24 * 60 * 60 * 1000); // 24 jam dalam milidetik | |
}); | |
req.on('error', (err) => { | |
console.error(`Error receiving file: ${err}`); | |
res.status(500).send('Error uploading file.'); | |
}); | |
}); | |
app.get('/:id/:filename', (req, res) => { | |
const filepath = path.join(__dirname, `/uploads/${req.params.id}-${req.params.filename}`); | |
res.download(filepath, req.params.filename, (err) => { | |
if (err) { | |
console.error(`Error downloading file: ${err}`); | |
res.status(404).send('File not found.'); | |
} | |
}); | |
}); | |
app.listen(7860, () => { | |
console.log('Server is running on port 7860'); | |
}); | |