Skip to content

Instantly share code, notes, and snippets.

@chrispage1
Created March 6, 2023 16:10
Show Gist options
  • Save chrispage1/6b642fab836c0bfc4867bac97f92336f to your computer and use it in GitHub Desktop.
Save chrispage1/6b642fab836c0bfc4867bac97f92336f to your computer and use it in GitHub Desktop.
Simple Express File Server
const bearerToken = 'secretTokenGoesHere';
const httpPort = 80;
// load in express & express fileUpload
const express = require('express'),
fileUpload = require('express-fileupload'),
app = express();
// initialise fileUpload plugin
app.use(fileUpload());
// when a post request comes into store, lets handle the file
app.post('/store', (req, res) => {
// verify the bearer token
const authToken = req.header('Authorization');
if (authToken?.split(' ')[1] !== bearerToken) {
return res.status(403).json({
success: false,
message: 'Unauthorized'
});
}
// check we have some files
if (req.files?.file) {
// move the file into our files directory
const file = req.files.file;
file.mv(__dirname + '/files/' + file.name);
// send a success message back
return res.send({
success: true,
message: 'File has been received',
})
}
// output an error message
return res.status(422).json({
success: false,
message: 'No file payload received'
});
});
// start listening
app.listen(httpPort, () => {
console.log('App is listening in port ' + httpPort);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment