3

We want to implement a functionality to upload multiple files into ExpressJS server and return all its unique urls, by an ajax call.

Following is the sample code in my front end:

var formData = new FormData();
for (var i = 0; i < nameId.length; i++) {
    if($(nameId[i])[0].files[0]){
        formData.append(nameId[i], $(nameId[i])[0].files[0], $(nameId[i])[0].files[0].name);
    }
}
$.ajax({
    url: '/upload-files',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(data){
        console.log('upload successful!');
        console.log(data);
    }
});

And in our router we have following code snippet to accept the request and store the file:

router.post('/upload-files',function(req, res, next){
    var form = new formidable.IncomingForm();
    form.multiples = true;
    form.uploadDir = path.join(__dirname, '/uploads');
    form.on('file', function(field, file) {
        console.log("File incoming");
        fs.rename(file.path, path.join(form.uploadDir, file.name));
    });
    form.on('error', function(err) {
        console.log('An error has occured: \n' + err);
    });
    form.on('end', function() {
        res.end('success');
    });
});

But, nothing ever happened in the router. Request is coming inside the router but after that nothing.

Is there anything wrong here? We are not getting any error in server side and in client side after long wait request is failing.

Please suggest. Thanks

2 Answers 2

2

I was able to resolve it by adding & updating following code snippets:

In the upload request processing function added code :

form.parse(req);

And in the app.js updated following code snippet to:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

to (To process multipart data seperatly)

app.use(bodyParser.json())
   .use(bodyParser.urlencoded());

NOTE Due to the change in parser following warning message is coming while starting the server:

body-parser deprecated undefined extended: provide extended option
1

My problem was solved by changing my ajax sending code as follow:-

     $.ajax({
            url: '/postroute',
            type: 'POST',
            processData: false,
            contentType: false,
            cache: false,
            data: formData,
            enctype: 'multipart/form-data',
            success: function(){
                console.log('Uploaded sucessfully');
            }
        });

Not the answer you're looking for? Browse other questions tagged or ask your own question.