Created
July 2, 2014 07:57
-
-
Save ybiquitous/f20225255eaca66619c1 to your computer and use it in GitHub Desktop.
Express 4.x file upload sample
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
/* jshint node: true, multistr: true */ | |
var express = require('express'); | |
var multer = require('multer'); | |
var serveIndex = require('serve-index'); | |
var serveStatic = require('serve-static'); | |
var app = express(); | |
var pubdir = 'public'; | |
app.use(function(req, res, next) { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Methods', 'POST'); | |
res.header('Access-Control-Allow-Headers', 'X-Requested-With'); | |
next(); | |
}); | |
app.use(multer({ | |
dest: pubdir + '/uploads/', | |
rename: function (fieldname, filename) { | |
return filename; | |
} | |
})); | |
app.get('/upload', function(req, res){ | |
res.send('<!DOCTYPE html><html lang="en">\ | |
<head>\ | |
<meta charset="UTF-8">\ | |
<title>Upload</title>\ | |
</head>\ | |
<body>\ | |
<form action="/upload" method="POST" enctype="multipart/form-data">\ | |
<input type="file" name="file"><input type="submit">\ | |
</form>\ | |
</body>\ | |
</html>'); | |
}); | |
app.post('/upload', function(req, res){ | |
console.log(req.files); | |
res.send(''); | |
}); | |
app.use(serveStatic(pubdir)); | |
app.use(serveIndex(pubdir, { view: 'details' })); | |
var server = app.listen(3000, function() { | |
console.log('Listening on port %d', server.address().port); | |
}); |
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": "express4x-file-upload-sample", | |
"version": "0.0.1", | |
"main": "index.js", | |
"license": "MIT", | |
"dependencies": { | |
"express": "^4.4.5", | |
"multer": "^0.1.0", | |
"serve-index": "^1.1.4", | |
"serve-static": "^1.3.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment