Search code examples
node.jsimagefile-uploadformidable

Image save not working in formidable when using 'file' for form.on


Following is the code which is working when I am using form.parse but it won't gets into form.on('file', ... Let me know what I am doing wrong here as I need to change the name of files before saving.

// CREATE
exports.upload = function (req, res) {

    var form = new formidable.IncomingForm();

    form.uploadDir = __dirname + '/upload';
    console.log("--FORM--");

    /*
    form.parse(req, function(err, fields, files) {
      console.log('received upload:\n\n');
      console.log(util.inspect({fields: fields, files: files}));
    });
    */
    form.on('file', function(field, file) {
        console.log("I am in file.");
        //rename the incoming file to the file's name
        //fs.rename(file.path, form.uploadDir + "/" + file.name);
    })


};

FYI - If I am using form.parse images are getting saved like 0382cb1bd421ee62b27dc431ab03270c as I want to rename it which is not working when trying to do it via form.on('file', ...).


Solution

  • I solved it using fileBegin to change the name, though you need to INCLUDE form.parse(req); to save the image.

    Working code -

    form.on('fileBegin', function(name, file) {
        file.path = form.uploadDir + "/" + file.name;
    })
    
    form.parse(req);