Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Formidable upload with XHR

I try to implement a simple XHR upload to Node.js (via Formidable). The problem is that if I set

xhr.setRequestHeader("Content-Type", "multipart/form-data");

node gives me error:

Error: bad content-type header, no multipart boundary

If I set boundary to just a random string nothing happens. The browser just hangs on POST and waits for server response.

The point is that if I use formidable with regular synchronous POST everything works fine.

Anyone tried to use Formidable with XHR upload?

like image 498
Pono Avatar asked Jul 30 '11 16:07

Pono


2 Answers

I figured it out. I made a small bug on the client side.

Here is the working expample of XHR upload with Formidable

You don't need to set any boundaries or special headers.

Client

var formData = new FormData();
var xhr = new XMLHttpRequest();

var onProgress = function(e) {
  if (e.lengthComputable) {
    var percentComplete = (e.loaded/e.total)*100;
  }
};

var onReady = function(e) {
 // ready state
};

var onError = function(err) {
  // something went wrong with upload
};

formData.append('files', file);
xhr.open('post', '/up', true);
xhr.addEventListener('error', onError, false);
xhr.addEventListener('progress', onProgress, false);
xhr.send(formData);
xhr.addEventListener('readystatechange', onReady, false);

Server

app.post('/up', function(req, res) {
  var form = new formidable.IncomingForm();
  form.uploadDir = __dirname + '/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);
    }
  });
});
like image 98
Pono Avatar answered Oct 14 '22 04:10

Pono


I tried a couple of different things with Formidable and was never able to get it to accept a XHR upload. Here is what I ended up doing for a file upload using express.

app.post('/upload', function (req,res){
  if(req.xhr){
    var fSize = req.header('x-file-size'),
    fType = req.header('x-file-type'), 
    basename = require('path').basename, 
    fName = basename(req.header('x-file-name')), 
    ws = fs.createWriteStream('./temp/'+fName); 
    req.on('data', function(data) { 
      ws.write(data);
    });

Hope this helps.

like image 31
scottmizo Avatar answered Oct 14 '22 03:10

scottmizo