Feras Odeh
Feras Odeh

Reputation: 9296

Ajax file upload with Node.js

I'm trying to use ajax file upload plugin(file uploader plugin) to upload a file to node.js server. This is my client side code to initialize plugin:

$(function() {
    /* dom ready */ 
  var uploader = new qq.FileUploader({
    // pass the dom node (ex. $(selector)[0] for jQuery users)
    element: document.getElementById('uploader'),
    // path to server-side upload script
    action: '/newitem',
    allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
    sizeLimit: 10000000
});
});

My server code is

  app.post('/newitem',function(req, res) {
      if(req.xhr) {
        console.log('Uploading...');
        var fName = req.header('x-file-name');
        var fSize = req.header('x-file-size');
        var fType = req.header('x-file-type');
        var ws = fs.createWriteStream('./'+fName)

        req.on('data', function(data) {
            console.log('DATA');
            ws.write(data);
        });
        req.on('end', function() {
            console.log('All Done!!!!');
            res.writeHead(200, { 'Content-Type': 'text/html' }); 
            res.end();
        });
    }

        });

My problem is that I can't get the progress updated and the uploader gives failed result for uploads while upload success. I think this is related to ajax server response Am I right? How could I fix it?

Thanks

Upvotes: 1

Views: 2888

Answers (1)

Sullof
Sullof

Reputation: 26

Change it with

   req.on('end', function() {
      res.writeHead(200, { 'Content-Type': 'application/json' }); 
      res.end(JSON.stringify({
          success: true
      }));
  });

Upvotes: 1

Related Questions