vsivsi / meteor-file-collection

Extends Meteor Collections to handle file data using MongoDB gridFS.
http://atmospherejs.com/vsivsi/file-collection
Other
159 stars 37 forks source link

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

Closed gbluntzer closed 6 years ago

gbluntzer commented 6 years ago

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.

vsivsi commented 6 years ago

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.

gbluntzer commented 6 years ago

Thank you for the response I will try Highland.