title: Node.js - Submit a part of a form using ajax and formidable
body: <p>In my node.js / express.js app, I try to post a part of a form using ajax.
  To achieve that, I read an example using <code>formidable</code> middleware.</p>
  
  <p>This is the HTML :</p>
  
  <pre><code>&lt;!-- some form elements --&gt;
  
  &lt;input type="file" id="upload_image" name="upload_image" /&gt;
  
  &lt;!-- other form elements with submit --&gt;
  </code></pre>
  
  <p>The client side javascript :</p>
  
  <pre><code>$(document).ready(function() {
  
      if(document.addEventListener) {
          document.getElementById("upload_image").addEventListener("change", function(e){
              uploadImages(e);
          });
      } else {
          document.getElementById("upload_image").attachEvent("onchange", function(e){
              uploadImages(e);
          });
      }
  
      function uploadImages(e) {
  
          var formData = new FormData();
          var xhr = new XMLHttpRequest();
  
          var onReady = function(e) {
              // ready state
              if(this.readyState == this.DONE) {
                  if(this.status != 200) {
                      console.log('error !!!');
                  } else {
                      if(xhr.responseText == 'success') {
                          console.log('succes !!!');
                      }
                  }
              }
          };
  
          var onError = function(err) {
              // something went wrong with upload
              console.log('error ...');
          };
  
          console.log(e.target.files[0]);
          formData.append('files', e.target.files[0]);
  
          xhr.open('post', "/markers/upload_image", true);
          xhr.addEventListener('error', onError, false);
          xhr.send(formData);
          xhr.addEventListener('readystatechange', onReady, false);
      }
  });
  </code></pre>
  
  <p>This is the server side :</p>
  
  <pre><code>router.post('/markers/upload_image', function (req, res) {
  
      //return console.log(req.files.files);
  
      var form = new formidable.IncomingForm();
      form.uploadDir = __dirname + 'client/tmp';
      form.encoding = 'binary';
  
      form.addListener('file', function(name, file) {
          // do something with uploaded file
      });
  
      form.addListener('end', function() {
          res.end();
      });
  
      form.parse(req, function(err, fields, files) {
          if (err) {
              console.log(err);
          }
      });
  
  });
  </code></pre>
  
  <p>Then, this is the result of the commented line <code>return console.log(req.files.files);</code>: </p>
  
  <pre><code>{ fieldName: 'files',
    originalFilename: 'myimage.jpg',
    path: '/var/folders/jb/jttwq52s7nn3s18_36y_xq300000gp/T/31093-14r558u.jpg',
    headers: 
     { 'content-disposition': 'form-data; name="files"; filename="vespa.jpg"',
       'content-type': 'image/jpeg' },
    ws: 
     { _writableState: 
        { highWaterMark: 16384,
          objectMode: false,
          needDrain: true,
          ending: true,
          ended: true,
          finished: true,
          decodeStrings: true,
          defaultEncoding: 'utf8',
          length: 0,
          writing: false,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function],
          writecb: null,
          writelen: 0,
          buffer: [],
          errorEmitted: false },
       writable: true,
       domain: null,
       _events: { error: [Object], close: [Object] },
       _maxListeners: 10,
       path: '/var/folders/jb/jttwq52s7nn3s18_36y_xq300000gp/T/31093-14r558u.jpg',
       fd: null,
       flags: 'w',
       mode: 438,
       start: undefined,
       pos: undefined,
       bytesWritten: 591626,
       closed: true },
    size: 591626,
    name: 'myimage.jpg',
    type: 'image/jpeg' }
  </code></pre>
  
  <p>What's wrong ? Any help would be very appreciate.</p>
  
  <p><strong>Edit</strong> : The returned error :</p>
  
  <pre><code>POST /markers/upload_image - - ms - -
  Error: Request aborted
  at IncomingMessage.onReqAborted (/Users/cedric/Projects/my-project/node_modules/express/node_modules/connect/node_modules/multiparty/index.js:182:17)
  at IncomingMessage.emit (events.js:117:20)
  at abortIncoming (http.js:1915:11)
  at Socket.serverSocketCloseListener (http.js:1927:5)
  at Socket.emit (events.js:117:20)
  at TCP.close (net.js:465:12)
  [Error: Request aborted]
  </code></pre>
  
  <p><strong>Edit</strong> : Trying the <a href="https://github.com/felixge/node-formidable" rel="nofollow">formidable's</a> doc example given the same error : </p>
  
  <pre><code>router.get('/test', function(req, res) {
  
      // show a file upload form
      res.writeHead(200, {'content-type': 'text/html'});
      res.end(
          '&lt;form action="/test" enctype="multipart/form-data" method="post"&gt;'+
          '&lt;input type="text" name="title"&gt;&lt;br&gt;'+
          '&lt;input type="file" name="upload" multiple="multiple"&gt;&lt;br&gt;'+
          '&lt;input type="submit" value="Upload"&gt;'+
          '&lt;/form&gt;'
       );
  
  });
  
  router.post('/test', function(req, res) {
  
      // parse a file upload
      var form = new formidable.IncomingForm();
  
      form.parse(req, function(err, fields, files) {
          res.writeHead(200, {'content-type': 'text/plain'});
          res.write('received upload:\n\n');
          res.end(util.inspect({fields: fields, files: files}));
      });
  
      return;
  
  });
  </code></pre>