Spaces:
Running
Running
const express = require('express'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const { v6: uuidv6 } = require('uuid'); | |
const app = express(); | |
const uploadDir = path.join(__dirname, 'uploads'); | |
// Pastikan direktori uploads ada | |
if (!fs.existsSync(uploadDir)) { | |
fs.mkdirSync(uploadDir); | |
} | |
app.put('/:filename', (req, res) => { | |
const shortId = uuidv6().slice(0, 5); // Menghasilkan ID pendek | |
const filename = req.params.filename; | |
const filepath = path.join(uploadDir, `${shortId}-${filename}`); | |
const fileStream = fs.createWriteStream(filepath); | |
req.pipe(fileStream); | |
fileStream.on('finish', () => { | |
const fileUrl = `https://dd5957d9-d77c-438b-8270-1fbf38f27e54-00-2459iusmnsrys.riker.replit.dev/${shortId}/${filename}`; | |
res.send(`Uploaded 1 file, ${req.headers['content-length']} bytes\n\nwget ${fileUrl}\n`); | |
// 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 | |
}); | |
fileStream.on('error', (err) => { | |
console.error(`Error writing file: ${err}`); | |
res.status(500).send('Error uploading file.'); | |
}); | |
}); | |
app.get('/:id/:filename', (req, res) => { | |
const filepath = path.join(uploadDir, `${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(3000, () => { | |
console.log('Server is running on http://localhost:3000'); | |
}); | |