forked from Sinzxc/FileStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (51 loc) · 1.68 KB
/
Copy pathindex.js
File metadata and controls
61 lines (51 loc) · 1.68 KB
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
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const port = 3000;
// Настраиваем место для сохранения файлов и их имена
const uploadsDir = path.join(__dirname, 'uploads');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
const upload = multer({ storage });
// Создаем директорию для загрузок, если её нет
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir);
}
app.get('/api/files', (req, res) => {
fs.readdir(uploadsDir, (err, files) => {
if (err) {
return res.status(500).json({ error: err.message });
}
const visible = files.filter((f) => !f.startsWith('.'));
res.json({ files: visible });
});
});
// Маршрут для загрузки файлов
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded.' });
}
res.json({ ok: true, filename: req.file.filename });
});
// Маршрут для получения файлов
app.get('/files/:filename', (req, res) => {
const safeName = path.basename(req.params.filename);
const filepath = path.join(uploadsDir, safeName);
if (fs.existsSync(filepath)) {
res.sendFile(filepath);
} else {
res.status(404).send('File not found.');
}
});
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});