gridfs.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // crowi-fileupload-gridFS
  2. module.exports = function(crowi) {
  3. 'use strict';
  4. var debug = require('debug')('growi:service:fileUploaderLocal')
  5. var fs = require('fs');
  6. var mongoose = require('mongoose');
  7. var gridfs = require('gridfs-stream');
  8. var path = require('path');
  9. var lib = {};
  10. var AttachmentFile = {};
  11. // instantiate mongoose-gridfs
  12. var gridfs = require('mongoose-gridfs')({
  13. collection: 'attachments',
  14. model: 'AttachmentFile',
  15. mongooseConnection: mongoose.connection
  16. });
  17. // obtain a model
  18. AttachmentFile= gridfs.model;
  19. // create or save a file
  20. lib.uploadFile = function (filePath, contentType, fileStream, options) {
  21. return new Promise(function (resolve, reject) {
  22. AttachmentFile.write({
  23. filename: 'test1.jpg',
  24. contentType: contentType
  25. },
  26. fs.createReadStream(fileStream.path),
  27. function (error, createdFile) {
  28. debug('Failed to upload ' + createdFile + 'to gridFS', error);
  29. resolve(createdFile);
  30. });
  31. });
  32. };
  33. // for larger file size
  34. // read a file and receive a stream
  35. // var stream = Attachment.readById(objectid);
  36. // for smaller file size
  37. // // read a file and receive a buffer
  38. // Attachment.readById(objectid, function (error, buffer) {
  39. // debug('Failed to read a file with ' + buffer, error);
  40. // });
  41. // // remove file details and its content from gridfs
  42. // Attachment.unlinkById(objectid, function (error, unlinkedAttachment) {
  43. // debug('Failed to remove ' + unlinkedAttachment + 'in gridFS', error);
  44. // });
  45. lib.generateUrl = function (filePath) {
  46. return path.posix.join('/uploads', filePath);
  47. };
  48. return lib;
  49. };