Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2012 04:45
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save xjamundx/1631025 to your computer and use it in GitHub Desktop.
Save xjamundx/1631025 to your computer and use it in GitHub Desktop.
file uploads with express and node.js
// 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 = "" + req.files.file.path.split("/").slice(-2).join("/")
req.body.path = req.files.file.path.split("/").slice(-2).join("/")
// 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
}) {
if (err) return res.send(err.message, 500)
Copy link

nicola commented Feb 5, 2013

In this way I can point at /whatever and you'll the req.file I send you through POST in your /uploads

Copy link

anwu commented Feb 8, 2013

Where do you get the new Photo object? Is it some additional node module?

Copy link

Siyfion commented Mar 15, 2013

@anwu I'd say it looks like a MongooseJS model object, but I could be wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment