Use multer for File-Uploads inside a Express Router

lukas293 picture lukas293 · Dec 13, 2015 · Viewed 9.2k times · Source

I got a working REST-API built with node.js and Express.

Now I need a file-upload endpoint, which accepts uploaded files and processes them.

I am using an Express Router and some Authentication middleware.

server.js (excerpt)

var router = express.Router()
app.use("/api", router)

[...]
router.use(function(req, res, next) {
    //Authentification middleware
    [...]
    next()
})

router.route("/upload")
     .post(function(req, res){
        //upload logic
     })

How can I use multer to serve the uploaded file as req.file (or so), but only in /api/upload and for authed users?

Answer

lukas293 picture lukas293 · Dec 13, 2015

Ok, I got it.

I can use

var multer = require("multer")
var upload = multer({ dest: "some/path" })

[...]

router.route("/upload")
    /* replace foo-bar with your form field-name */
    .post(upload.single("foo-bar"), function(req, res){
       [...]
    })