Search code examples
javascriptnode.jsexpressxmlhttprequestmulter

How to save file using Express 4 and Multer?


I'm trying to save incoming file from FormData xhr request but i can't even parse incoming request. This is how i'm trying to send file:

...
    let xhr = new XMLHttpRequest(),
    formData = new FormData();

    for(let i = 0; i < this.files.length; i++) {
        formData.append(this.files[i], this.files[i].name);
    }
    xhr.open('POST', URL, true);
    xhr.send(formData);
...

And this is how i'm trying to catch it:

var express = require('express');
var router = express.Router();
var multer  = require('multer');
var uploads = multer({dest: './uploads/'});

router.post('/upload', uploads.any(), function (req, res) {
    console.log(req.files); // []
    console.log(req.file); // undefined
    console.log(req.body); //{ '[object File]': '20160715_104330.jpg' }
});

The image comes on the server but is not writing to the directory uploads.

How I can save the image in the directory uploads?


Solution

  • I found the error. The following is the corrected code line:

    formData.append( 'Choose your Fieldname', this.files[i], this.files[i].name);
    

    I just needed to put the first parameter is a string representing the fieldname.

    See the result in the backend:

    var express = require('express');
    var router = express.Router();
    var multer  = require('multer');
    var uploads = multer({dest: './uploads/'});
    
    router.post('/upload', uploads.any(), function (req, res) {
        console.log(req.files); 
        /* [ { fieldname: 'Choose your Fieldname',
               originalname: '20160715_104330.jpg',
               encoding: '7bit',
               mimetype: 'image/jpeg',
               destination: './uploads/',
               filename: '72b7a52101537ab1006f4feb0fa752be',
               path: 'uploads\\72b7a52101537ab1006f4feb0fa752be',
               size: 233509 } ]
         */
        console.log(req.file); // undefined
        console.log(req.body); //{}
    });
    

    Below is a smaller code in the frontend:

    ...
        upload(){
            let xhr = new XMLHttpRequest(),
            formData = new FormData();
            formData.append('Choose your Fieldname', this.files[0], this.files[0].name);
            xhr.open('POST', URL, true);
            xhr.send(formData);
        }
    ...