How to change upload path when use formidable with express in node.js

hh54188 picture hh54188 · Dec 24, 2012 · Viewed 7.1k times · Source

Actually I come across two problem

First, how to change the upload path

my folder structure is like this:

|__app.js
|__upload

my node code is in app.js and boot from it, so I want to the upload image upload to the upload folder, I change the path:

var form = new formidable.IncomingForm;
form.uploadDir = "./upload";

It seems it upload successed, but I don't know where the file go, it doesn't in the upload folder.

So what the correct path name?

The second problem is

If I don't change it, it could upload correctly to the C:/Users/ADMINI~1/AppData/Local/Temp but it will be renamed without the foramt,

so how can I get the upload format and renamed by myself?

The third problem is

I also bind handler to the process event, like

form.on('progress', function(bytesReceived, bytesExpected) {
    console.log(bytesReceived + ' ' + bytesExpected);
});

but it seems doesn't work,when upload log nothing. why?Do I missing something?

Here is my all code:

app.post('/upload', function (req, res) {
    var form = new formidable.IncomingForm;
    // form.uploadDir = "./upload";
    console.log(form.uploadDir);

    form.parse(req, function(err, fields, files){
      if (err) return res.end('You found error');
      console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end('error:\n\n'+util.inspect(err));
    });

    // res.end('Done');
    res.send("well done");

    return;
})

Answer

zemirco picture zemirco · Dec 27, 2012

First of all you have to tell your app that you don't want the bodyParser to handle file uploads.

app.use(express.bodyParser());

is equivalent to

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

Remove the last line to deal with file uploads yourself. Add some custom options when initializing your form

var form = new formidable.IncomingForm({ 
  uploadDir: __dirname + '/tmp',  // don't forget the __dirname here
  keepExtensions: true
});

Now your code should work.