Skip to content

Instantly share code, notes, and snippets.

@Pigpog
Created August 28, 2018 04:07
Show Gist options
  • Save Pigpog/671b29ae39568ce39005c48f8bbbf60a to your computer and use it in GitHub Desktop.
Save Pigpog/671b29ae39568ce39005c48f8bbbf60a to your computer and use it in GitHub Desktop.
A very simple upload server for nodejs.
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// default options
app.use(fileUpload());
app.get("/upload", function (req, res, next) {
console.log(req.connection.remoteAddress)
try {
res.send(`
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>`
)
} catch (e) {
next(e)
}
})
app.post('/upload', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv("recievedfiles/"+sampleFile.name, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
app.listen(process.env.PORT || 3000, function () {
console.log('Listening on http://localhost:' + (process.env.PORT || 3000))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment