File size: 1,717 Bytes
70e4b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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');
});