createOnAfterUpload.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Meteor } from 'meteor/meteor';
  2. import fs from 'fs';
  3. export const createOnAfterUpload = function onAfterUpload(filesCollection, bucket, file, versionName) {
  4. const self = filesCollection;
  5. const metadata = { ...file.meta, versionName, fileId: file._id };
  6. fs.createReadStream(file.versions[versionName].path)
  7. // this is where we upload the binary to the bucket using bucket.openUploadStream
  8. // see http://mongodb.github.io/node-mongodb-native/3.2/api/GridFSBucket.html#openUploadStream
  9. .pipe(
  10. bucket.openUploadStream(file.name, {
  11. contentType: file.type || 'binary/octet-stream',
  12. metadata,
  13. }),
  14. )
  15. // and we unlink the file from the fs on any error
  16. // that occurred during the upload to prevent zombie files
  17. .on('error', err => {
  18. console.error("[createOnAfterUpload error]", err);
  19. self.unlink(self.collection.findOne(file._id), versionName); // Unlink files from FS
  20. })
  21. // once we are finished, we attach the gridFS Object id on the
  22. // FilesCollection document's meta section and finally unlink the
  23. // upload file from the filesystem
  24. .on(
  25. 'finish',
  26. Meteor.bindEnvironment(ver => {
  27. const property = `versions.${versionName}.meta.gridFsFileId`;
  28. self.collection.update(file._id, {
  29. $set: {
  30. [property]: ver._id.toHexString(),
  31. },
  32. });
  33. self.unlink(self.collection.findOne(file._id), versionName); // Unlink files from FS
  34. }),
  35. );
  36. };