Add file upload functionality
This commit is contained in:
parent
5e4554710c
commit
f3c3f15f3a
6 changed files with 217 additions and 5 deletions
|
@ -1,6 +1,8 @@
|
|||
import cors from 'cors';
|
||||
import dotenv from 'dotenv';
|
||||
import express from 'express';
|
||||
import formidable from 'formidable';
|
||||
import { mkdir, rename } from 'fs/promises';
|
||||
const app = express();
|
||||
|
||||
dotenv.config();
|
||||
|
@ -15,8 +17,33 @@ app.listen(+process.env.API_PORT, () => console.log(`Server running on: ${proces
|
|||
app.use(express.json());
|
||||
app.use(cors({ origin: process.env.CORS_HOST }));
|
||||
|
||||
// Register post route
|
||||
// app.post('/api/register', () => { });
|
||||
// File upload post route
|
||||
app.post('/api/upload', (req, res) => {
|
||||
const form = new formidable.IncomingForm();
|
||||
form.parse(req, (err, fields, files) => {
|
||||
if (!('filepath' in files.filetoupload) || !files.filetoupload?.filepath) {
|
||||
res.write('Ups! Missing property "filetoupload" file');
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const filename = files.filetoupload.originalFilename
|
||||
const oldpath = files.filetoupload.filepath
|
||||
const newdir = process.cwd() + '/upload/'
|
||||
const newpath = newdir + filename
|
||||
mkdir(newdir, { recursive: true })
|
||||
.then(() => {
|
||||
return rename(oldpath, newpath)
|
||||
})
|
||||
.then(() => {
|
||||
console.log('New Upload: ' + filename)
|
||||
res.write('File uploaded and moved!');
|
||||
res.end();
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err) throw err;
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// - - - - -
|
||||
|
@ -49,6 +76,6 @@ io.on("connection", (socket) => {
|
|||
console.log("Got test:", payload)
|
||||
// ...
|
||||
});
|
||||
|
||||
|
||||
socket.emit('test2', 'lol')
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue