File size: 2,017 Bytes
2a727d3
 
 
1049aa6
2a727d3
 
1049aa6
2a727d3
 
1049aa6
 
 
2a727d3
 
 
1049aa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a727d3
 
 
1049aa6
 
 
 
 
 
 
 
 
2a727d3
 
1049aa6
 
2a727d3
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
54
55
56
57
58
59
60
61
62
63
64
65
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const MemoryFS = require('memory-fs');
const http = require('http'); // Import http
const fs = require('fs');


const app = express();
const memFs = new MemoryFS();
const port = process.env.PORT || 7860; // Ambil port dari env atau default

const server = http.createServer(app);


app.put('/:filename', (req, res) => {
  const shortId = uuidv4().slice(0, 5); // Menghasilkan ID pendek
  const filename = req.params.filename;
  const filepath = `/${shortId}-${filename}`;
  const chunks = [];

  req.on('data', chunk => {
    chunks.push(chunk);
  });

  req.on('end', () => {
    const fileBuffer = Buffer.concat(chunks);
    memFs.writeFileSync(filepath, fileBuffer);

    const protocol = req.protocol; // Mengambil protokol dari request (http atau https)
    let host = req.get('host'); // Mengambil host dari request
    let filePort = protocol === 'https' ? 443 : 80; // Default port untuk http dan https
    if (host.includes(':')) {
        [host, filePort] = host.split(':');
    }

    const fileUrl = `${protocol}://${host}:${filePort}/${shortId}/${filename}`;
    res.send(`Uploaded 1 file, ${fileBuffer.length} bytes\n\nwget ${fileUrl}\n`);

    // Hapus file setelah 24 jam
    setTimeout(() => {
      memFs.unlinkSync(filepath);
    }, 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 = `/${req.params.id}-${req.params.filename}`;
  try {
    const fileBuffer = memFs.readFileSync(filepath);
    res.setHeader('Content-Disposition', `attachment; filename="${req.params.filename}"`);
    res.send(fileBuffer);
  } catch (err) {
    console.error(`Error downloading file: ${err}`);
    res.status(404).send('File not found.');
  }
});

server.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});