user3046205
user3046205

Reputation: 131

How can i upload multiple files in node.js?

I need help in upload multiple files using node.js upload file reader.

I am using the fs = require('fs'). I have problem in choose two files,only one file only write in upload directory.

This is my backend

var files = req.files.files[0];
for (var i = 0; i < files.length; i++) {    
  file = files[i];
  fs.readFile(files[i].path, function(error, data) {
    // console.log( files[i].path ) ,here displayed two same both
    fs.writeFile(uploadDirectory() + newFileName, data, function(error) {
    });
  });
}

Please help me. what is the problem in my code. Thanks.

Upvotes: 1

Views: 4698

Answers (1)

suish
suish

Reputation: 3343

You should avoid using files[i] in asynchronous function's callback which is directly written inside of for-loop. the reason why console.log( files[i].path ) displays same thing twice is because when the code is loaded,the for-loop has already done. so you always get the last element of the array.

the easiest way to fix that is making a new scope(function)

for (var i = 0; i < files.length; i++) {    
  readAndWriteFile(files[i]);
}

var readAndWriteFile = function(file){
    fs.readFile(file.path, function(error, data) {
    // console.log( file.path ) displays what you expect.
    fs.writeFile(/* define new file name */, data, function(error) {
    });
  });
}

Upvotes: 1

Related Questions