Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
})
like image 597
hh54188 Avatar asked Dec 24 '12 14:12

hh54188


People also ask

How do I change the path of a node js file?

js: var fs = require('fs') var newPath = "E:\\Thevan"; var oldPath = "E:\\Thevan\\Docs\\something. mp4"; exports. uploadFile = function (req, res) { fs. readFile(oldPath, function(err, data) { fs.


1 Answers

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.

like image 125
zemirco Avatar answered Sep 29 '22 20:09

zemirco