Skip to content
Snippets Groups Projects
Commit 3146b1ba authored by Anthropy's avatar Anthropy
Browse files

added an initial version which can down/upload files and fetch metadata from the /files/ endpoint

parent 6e53a283
Branches
No related tags found
No related merge requests found
const express = require('express');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const config = require('./config.json');
const app = express();
const upload = multer({ dest: config.storageDirectory });
// Endpoint to upload files
app.post('/upload', upload.single('file'), async (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send("No file uploaded");
}
const metadata = req.body.metadata || {};
const metadataPath = path.join(config.metadataDirectory, file.originalname);
try {
fs.writeFileSync(metadataPath, JSON.stringify(metadata));
res.send("File uploaded successfully");
} catch (e) {
res.status(500).send(e.message);
}
});
// Endpoint to fetch file info and download link
app.get('/files/*', async (req, res) => {
const fileName = req.params[0];
const filePath = path.join(config.storageDirectory, fileName);
const metadataPath = path.join(config.metadataDirectory, fileName);
try {
if (fs.existsSync(filePath)) {
const metadata = fs.existsSync(metadataPath) ?
JSON.parse(fs.readFileSync(metadataPath, 'utf8')) :
{ message: "No metadata found for this file" };
res.setHeader('Content-Type', 'application/json');
res.json({
fileName,
metadata,
downloadUrl: `http://${req.headers.host}/download/${fileName}`
});
} else {
res.status(404).send("File not found");
}
} catch(e) {
res.status(500).send(e.message);
}
});
// Endpoint to download file
app.get('/download/*', (req, res) => {
const fileName = req.params[0];
const filePath = path.join(config.storageDirectory, fileName);
if (fs.existsSync(filePath)) {
res.download(filePath);
} else {
res.status(404).send("File not found");
}
});
app.listen(3000, () => console.log('App is listening on port 3000'));
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment