Meteor - What's the best way to get files from a post request?

554 views Asked by At

I'm currently using the redactor wysiwyg, which has an image upload implementation that sends a post request to a given url then expects back some JSON like: { "filelink": "/static/img.jpg" } in order to display the uploaded image.

My current approach has been to create a server-side route, which would get the image from the request body, send it to s3, save the meta data (collectionFS), then return the necessary JSON via the response.

I've instantiated redactor like this:

Template.editor.rendered = function() {
  $("#editor").redactor({
  imageUpload: "s3"
  });
};

And the server-side router looks like this:

Router.route('/s3', function () {
  this.response.setHeader("Content-Type", "text/html");
  var data = JSON.stringify(this.request.body;
  var res = this.response;
  res.end(data);
  }, {where: 'server'}
);

Unfortunately, this returns a blank JSON object. I have tried with request.files and request.body.files, but these don't work.

I know the route is working, because I can send plain html via the response. And, I can definitely see binary data of the uploaded file in the post request in firebug, but I can't seem to get Meteor to get those files.

1

There are 1 answers

1
Hubert OG On

The POST data is not available at the time the middleware is called, but instead it is received in data events. You need to handle those events to get your file data. Example:

Router.route('...', function() {
  var buffers = [];
  var totalLength = 0;

  this.request.on('error', function(err) {
    // handle network error here
  });

  this.request.on('data', function(chunk) {
    buffers.push(chunk);
    totalLength += chunk.length;
    if(totalLength > SOME_LARGE_CONSTANT) {
      // handle data overflow here
    }
  });

  this.request.on('end', function() {
    var data = Buffer.concat(buffers);
    // handle properly received data here
  });

});