vsivsi/meteor-file-collection

Example of Pulling file from collection to be sent to external server

gbluntzer opened this issue · 2 comments

Thanks for making this package. This is not an issue but rather a question.
I would like to be able to pull a file from the file collection and send it as a multipart form to another server
Do you have a example of how to get the data of the file and send it

I was trying the following but having no luck. I cant figure out what to do with inputFileData :
requestJSON has two parts one is a json (jsonDoc) message with data about what the file is for
the other part is the file itself. When the other server gets the request the file data is just text file whos content is "[Object]" instead of the image file.

Code

let inputFileMeta = Ready.collections.images.collection.findOne({ filename: 'auto.jpeg' });
let inputFileData = Ready.collections.images.collection.findOneStream({ filename: 'auto.jpeg' });
...
let requestJSON = this.buildMultipartFormData(authValue, jsonDoc, inputFileMeta, inputFileData);
...
buildMultipartFormData(authValue, jsonDoc, inputFileMeta, inputFileData) {
let boundary = '----' + (new Date()).getTime();
let bodyString = [];
bodyString.push(
'--' + boundary,
'Content-Disposition: form-data; name="file"; filename="' + inputFileMeta.filename + '"',
//'Content-type: ' + 'image/jpeg',
'Content-type: ' + inputFileMeta.contentType,
'',
inputFileData);

bodyString.push(
    '--' + boundary,
    'Content-Disposition: form-data; name="json"; filename=""',
    'Content-Type: application/json',
    '',
    JSON.stringify(jsonDoc)
);

bodyString.push('--' + boundary + '--', '');

return {
  content: bodyString.join('\r\n'),
  headers: {
    'Content-Type': 'multipart/form-data; boundary=' + boundary
  },
  auth: authValue,
}

}

...
Meteor.http.call("POST",externalServerURL, requestJSON);

Thanks for any help.

In your example above inputFileData is a node.js Readable Stream object.

So you will either need to use an HTTP multipart request library that knows how to deal with such standard stream objects for file data, or copy the stream data chunks yourself into an appropriately sized Buffer object (or whatever the library you are using expects...)

Dealing with streams is an elemental part of understanding how node.js works. You will be well served by taking the time to learn about them in detail. There are many npm packages to make using streams more convenient. I currently recommend Highland as a good place to start.

Hope that helps.

Thank you for the response I will try Highland.