Uploading files with express.js is insanely simple!
FYI, there's something special called req.files when you upload multipart forms. In this case I upload the file with a form field with the name of "file".
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
// middleware | |
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + "/public/uploads" })) | |
// later | |
app.get('/photos', uploadFile, addPhoto) | |
// file is automatically saved to /public/uploads, let's just set | |
function uploadFile(req, res, next) { | |
if (req.files) { | |
req.body.url = "http://myawesomesite.com/" + req.files.file.path.split("/").slice(-2).join("/") | |
req.body.path = req.files.file.path.split("/").slice(-2).join("/") | |
} | |
next() | |
} | |
// file upload is optional, it could have come before | |
function addPhoto(req, res) { | |
var eventId = req.param("eventId") | |
var e = req.body | |
var userId = e.userId ? new ObjectId(e.userId) : undefined | |
var photo = new Photo({ | |
userId : userId | |
, eventId : new ObjectId(e.eventId) | |
, latitude : e.latitude | |
, longitude : e.longitude | |
, path : e.path | |
, url : e.url | |
, type : e.type | |
, title : e.title | |
, description : e.description | |
}) | |
photo.save(function(err) { | |
if (err) return res.send(err.message, 500) | |
res.json("OK") | |
}) | |
} |
I found this stuff out here:
https://groups.google.com/forum/#!topic/express-js/vDmtdWMx5tY
Nice post man, I used it today:D
ReplyDelete