Spaces:
Running
Running
const express = require('express'); | |
const { v4: uuidv4 } = require('uuid'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const app = express(); | |
const UPLOAD_DIR = path.join(__dirname, 'uploads'); // Folder untuk menyimpan file | |
// Pastikan folder upload ada | |
if (!fs.existsSync(UPLOAD_DIR)) { | |
fs.mkdirSync(UPLOAD_DIR); | |
} | |
app.put('/:filename', (req, res) => { | |
const shortId = uuidv4(); // Gunakan UUID penuh | |
const filename = req.params.filename; | |
const fileDir = path.join(UPLOAD_DIR, shortId); // Folder khusus per upload | |
const filepath = path.join(fileDir, filename); | |
// Buat folder untuk file ini | |
fs.mkdirSync(fileDir, { recursive: true }); | |
const writeStream = fs.createWriteStream(filepath); | |
let bytesReceived = 0; | |
req.on('data', chunk => { | |
writeStream.write(chunk); | |
bytesReceived += chunk.length; | |
}); | |
req.on('end', () => { | |
writeStream.end(); // Menutup stream, file selesai ditulis | |
console.log(`Uploaded file ${filename}, ${bytesReceived} bytes to ${filepath}`); | |
const fileUrl = `https://zhofang-temp-storage.hf.space/${shortId}/${filename}`; | |
res.send(`Uploaded 1 file, ${bytesReceived} bytes\n\nwget ${fileUrl}\n`); | |
// Hapus file dan folder setelah 24 jam | |
setTimeout(() => { | |
fs.rm(fileDir, { recursive: true, force: true }, (err) => { | |
if (err) { | |
console.error(`Error deleting file and folder at ${fileDir}:`, err); | |
} else { | |
console.log(`File and folder at ${fileDir} deleted successfully`); | |
} | |
}); | |
}, 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.'); | |
}); | |
writeStream.on('error', (err) => { | |
console.error(`Error writing file: ${err}`); | |
res.status(500).send('Error uploading file.'); | |
fs.rm(fileDir, { recursive: true, force: true }, (err) => { | |
if (err) { | |
console.error(`Error deleting file and folder after write error at ${fileDir}:`, err); | |
} else { | |
console.log(`File and folder at ${fileDir} deleted due to error`); | |
} | |
}); | |
}); | |
}); | |
app.get('/:id/:filename', (req, res) => { | |
const fileDir = path.join(UPLOAD_DIR, req.params.id); | |
const filepath = path.join(fileDir, req.params.filename); | |
console.log(`Attempting to download file: ${filepath}`); | |
fs.readFile(filepath, (err, fileBuffer) => { | |
if (err) { | |
console.error(`Error downloading file at ${filepath}:`, err); | |
res.status(404).send('File not found.'); | |
} else { | |
res.setHeader('Content-Disposition', `attachment; filename="${req.params.filename}"`); | |
res.send(fileBuffer); | |
} | |
}); | |
}); | |
app.listen(7860, () => { | |
console.log('Server is running on http://localhost:7860'); | |
}); |