7

Anyone knows why the "rename" function (and all other multer callbacks) are not working?

var express = require('express');
var multer  = require('multer');

var app = express();

app.use(multer({
    dest: 'uploads/',
    rename: function (fieldname, filename) {
        return new Date().getTime();
    },
    onFileUploadStart: function (file) {
        console.log(file.name + ' is starting ...');
    },
    onFileUploadComplete: function (file, req, res) {
        console.log(file.name + ' uploading is ended ...');
        console.log("File name : "+ file.name +"\n"+ "FilePath: "+ file.path)
    },
    onError: function (error, next) {
        console.log("File uploading error: => "+error)
        next(error)
    },
    onFileSizeLimit: function (file) {
        console.log('Failed: ', file.originalname +" in path: "+file.path)
        fs.unlink(path.join(__dirname, '../tmpUploads/') + file.path) // delete the partially written file
    }
}).array('photos', 12));



app.listen(8080,function(){
    console.log("Working on port 8080");
});

app.get('/',function(req,res){
    res.sendFile(__dirname + "/index.html");
});


app.post('/photos/upload', function (req, res, next) {
    // req.files is array of `photos` files
    // req.body will contain the text fields, if there were any
    //console.log(req.files);
    //console.log(req.body);
    res.json(req.files)

});
Ashraf Fayad
  • 1,433
  • 4
  • 17
  • 31

2 Answers2

10

It seems the usage has been changed over time. Currently, multer constructor only accepts following options (https://www.npmjs.com/package/multer#multer-opts):

  • dest or storage - Where to store the files
  • fileFilter - Function to control which files are accepted
  • limits - Limits of the uploaded data

So, for example the renaming is to be solved by configuring appropriate storage (https://www.npmjs.com/package/multer#storage).

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads'); // Absolute path. Folder must exist, will not be created for you.
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
})

var upload = multer({ storage: storage });

app.post('/profile', upload.single('fieldname'), function (req, res, next) {
    // req.body contains the text fields 
});

The fieldname must match the field name in the request body. That is, in case of HTML form post, the form upload element input name.

Also have a look for other middleware functions like array and fields - https://www.npmjs.com/package/multer#single-fieldname which provide a a little different functionality.

Also you may be interested in the limits (https://www.npmjs.com/package/multer#limits) and file filter (https://www.npmjs.com/package/multer#filefilter)

And also - source is the single source of truth - have a peek!(https://github.com/expressjs/multer/blob/master/index.js)

tiblu
  • 2,959
  • 1
  • 22
  • 22
  • Oh, seems I did not save the or somehow reverted the working example. Updated, this one should be sufficient. Basically a sample from the manual. Thanks for pointing it out. – tiblu Sep 05 '15 at 22:14
  • i am doing the same thing which you have wriiten above but it is not saving any image but when i write only this, var upload = multer({ dest: 'uploads/' }); then it works but i am now not able to save file with any particular file extension ?? – Sudhanshu Gaur Sep 05 '15 at 22:22
  • 1
    The ``destination`` callback function needs to return absolute path. So for you following should work - ``cb(null, __dirname + '/uploads')`` - this will save files to the ``uploads`` subfolder in the same directory where the currently running script is. See ``__dirname`` in Node.JS manual - https://nodejs.org/docs/latest/api/globals.html#globals_dirname Will add edit my answer and add comment. – tiblu Sep 05 '15 at 22:45
  • 1
    actually problem is not about folder problem is that code below destination which is filename does not work never gets called ?? PLS Help me i have spent days and nothing is happening.... – Sudhanshu Gaur Sep 05 '15 at 23:16
  • @SudhanshuGaur Show me your code. Both the font-end HTML and backend. Make a new SO question maybe? – tiblu Sep 05 '15 at 23:19
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/88900/discussion-between-sudhanshu-gaur-and-tiblu). – Sudhanshu Gaur Sep 05 '15 at 23:32
  • Actually overall problem was i wasnt creating a folder first, thanks a lot for ur help.................. :) – Sudhanshu Gaur Sep 06 '15 at 02:14
  • for uploading array of pics do i have to define this number of pics user is uploading like here .array('photos', 12)) as because i dont know how many pics user is uploading and how can i change this variable dynamically ?? – aman verma Sep 28 '15 at 15:57
  • The signature is ``.array(fieldname[, maxCount])`` meaning you do not have to specify a count at all. - https://www.npmjs.com/package/multer#multer-opts – tiblu Sep 28 '15 at 18:48
  • Is there any callback to know when the file is saved? – Gil Beyruth Jan 06 '17 at 01:41
0

Its a windows issue. Date as ISOString used as file name is not allowed in windows and violates some CORS policy. So for that there is a node package called uuid which does the job.

Nimdp
  • 1