createOnAfterUpload.js 1.8 KB

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