Created
July 2, 2017 13:05
-
-
Save Sorebit/a0d523fd2b1361b906a60a8c5d42a00d to your computer and use it in GitHub Desktop.
Node.js file uploader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>File uploader</title> | |
</head> | |
<body> | |
<form id="uploadForm" enctype="multipart/form-data" action="/api/status" method="post"> | |
<input type="file" name="user-upload" /> | |
<input type="submit" value="Upload File" name="submit"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "file-uploader", | |
"version": "1.0.0", | |
"description": "Simple file uploader", | |
"main": "server.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Sorebit", | |
"license": "ISC", | |
"dependencies": { | |
"express": "^4.15.2", | |
"multer": "^1.3.0" | |
}, | |
"devDependencies": { | |
"mocha": "^3.3.0", | |
"should": "^11.2.1", | |
"supertest": "^3.0.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PORT = 3000; | |
var express = require("express"); | |
var multer = require('multer'); | |
var app = express(); | |
var storage = multer.diskStorage({ | |
destination: function(req, file, callback) { | |
callback(null, './uploads'); | |
}, | |
filename: function(req, file, callback) { | |
callback(null, file.fieldname + '-' + Date.now()); | |
} | |
}); | |
var upload = multer({storage: storage}, {limits: {fileSize: 10000000}}).single('user-upload'); | |
app.get('/', function(req, res) { | |
res.sendFile(__dirname + "/index.html"); | |
}); | |
app.post('/api/status', function(req,res) { | |
upload(req, res, function(err) { | |
if(err) { | |
return res.end("Error uploading file."); | |
} | |
res.end("File uploaded."); | |
}); | |
}); | |
app.listen(PORT, function() { | |
console.log("Server listening on port", PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment