18

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?

lukas293
  • 518
  • 1
  • 3
  • 15

3 Answers3

22

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){
       [...]
    })
lukas293
  • 518
  • 1
  • 3
  • 15
8

For me, it also worked.

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

router.post("/upload", upload.single("foo-bar"), function(req, res) {
  ...
}
Pei
  • 11,452
  • 5
  • 41
  • 45
  • 2
    I spent a whole lot of time trying to make this work. `var uploadMulter = multer({ dest: directory }); router.post('/upload', uploadMulter.single("html_input_element_name"), function(req,res, next) {...` . There is a line in the Multer repo `In an average web app, only dest might be required,` . Don't believe that line... you also need the `.single(fieldname)` call... Many thanks... – zipzit May 31 '18 at 04:49
2

In my case i try every thing but it not works but i come over the solution

app.js

const multer  = require('multer');
const storage =  {
    dest:  'UPLOAD/PATH/'
}
const upload = multer(storage);
app.post('/myupload', upload.single('FILE_NAME'), (req,res)=>{
  res.send('Upload');
});

i tried many times with express.Router() but it not works that's why i write code in app.js and redirect to another file.

Renish Gotecha
  • 2,232
  • 22
  • 21