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

拈花ヽ惹草 提交于 2019-12-06 00:28:02

问题


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;
})

回答1:


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.



来源:https://stackoverflow.com/questions/14022353/how-to-change-upload-path-when-use-formidable-with-express-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!