Spaces:
Running
Running
Update temp.js
Browse files
temp.js
CHANGED
@@ -1,48 +1,66 @@
|
|
|
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const express = require('express');
|
2 |
+
const { v4: uuidv4 } = require('uuid');
|
3 |
+
const fs = require('fs');
|
4 |
+
const path = require('path');
|
5 |
|
6 |
+
const app = express();
|
7 |
+
const storageDir = path.join(__dirname, 'uploads');
|
8 |
+
|
9 |
+
// Ensure the storage directory exists
|
10 |
+
if (!fs.existsSync(storageDir)) {
|
11 |
+
fs.mkdirSync(storageDir);
|
12 |
+
}
|
13 |
+
|
14 |
+
app.put('/:filename', (req, res) => {
|
15 |
+
const shortId = uuidv4().slice(0, 5); // Generate a short ID
|
16 |
+
const filename = req.params.filename;
|
17 |
+
const filepath = path.join(storageDir, `${shortId}-${filename}`);
|
18 |
+
const chunks = [];
|
19 |
+
|
20 |
+
req.on('data', chunk => {
|
21 |
+
chunks.push(chunk);
|
22 |
+
});
|
23 |
+
|
24 |
+
req.on('end', () => {
|
25 |
+
const fileBuffer = Buffer.concat(chunks);
|
26 |
+
|
27 |
+
fs.writeFile(filepath, fileBuffer, (err) => {
|
28 |
+
if (err) {
|
29 |
+
console.error(`Error writing file: ${err}`);
|
30 |
+
return res.status(500).send('Error uploading file.');
|
31 |
+
}
|
32 |
+
|
33 |
+
const fileUrl = `https://zhofang-temp-storage.hf.space/${shortId}/${filename}`;
|
34 |
+
res.send(`Uploaded 1 file, ${fileBuffer.length} bytes\n\nwget ${fileUrl}\n`);
|
35 |
+
|
36 |
+
// Delete the file after 24 hours
|
37 |
+
setTimeout(() => {
|
38 |
+
fs.unlink(filepath, (err) => {
|
39 |
+
if (err) console.error(`Error deleting file: ${err}`);
|
40 |
+
});
|
41 |
+
}, 24 * 60 * 60 * 1000); // 24 hours in milliseconds
|
42 |
+
});
|
43 |
+
});
|
44 |
+
|
45 |
+
req.on('error', (err) => {
|
46 |
+
console.error(`Error receiving file: ${err}`);
|
47 |
+
res.status(500).send('Error uploading file.');
|
48 |
+
});
|
49 |
+
});
|
50 |
+
|
51 |
+
app.get('/:id/:filename', (req, res) => {
|
52 |
+
const filepath = path.join(storageDir, `${req.params.id}-${req.params.filename}`);
|
53 |
+
fs.readFile(filepath, (err, fileBuffer) => {
|
54 |
+
if (err) {
|
55 |
+
console.error(`Error downloading file: ${err}`);
|
56 |
+
return res.status(404).send('File not found.');
|
57 |
+
}
|
58 |
+
|
59 |
+
res.setHeader('Content-Disposition', `attachment; filename="${req.params.filename}"`);
|
60 |
+
res.send(fileBuffer);
|
61 |
+
});
|
62 |
+
});
|
63 |
+
|
64 |
+
app.listen(7860, () => {
|
65 |
+
console.log('Server is running on port 7860');
|
66 |
+
});
|