gridfs.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // delete a file
  20. lib.deleteFile = function (fileId, filePath) {
  21. debug('File deletion: ' + fileId);
  22. return new Promise(function (resolve, reject) {
  23. AttachmentFile.unlinkById(fileId, function (error, unlinkedAttachment) {
  24. resolve();
  25. });
  26. });
  27. };
  28. // create or save a file
  29. lib.uploadFile = function (filePath, contentType, fileStream, options) {
  30. return new Promise(function (resolve, reject) {
  31. AttachmentFile.write({
  32. filename: filePath,
  33. contentType: contentType
  34. },
  35. fs.createReadStream(fileStream.path),
  36. function (error, createdFile) {
  37. debug('Failed to upload ' + createdFile + 'to gridFS', error);
  38. resolve(createdFile._id);
  39. });
  40. });
  41. };
  42. // // for larger file size
  43. // // read a file and receive a stream
  44. // var stream = Attachment.readById(objectid);
  45. // // for smaller file size
  46. // // read a file and receive a buffer
  47. // Attachment.readById(objectid, function (error, buffer) {
  48. // debug('Failed to read a file with ' + buffer, error);
  49. // });
  50. // // remove file details and its content from gridfs
  51. // Attachment.unlinkById(objectid, function (error, unlinkedAttachment) {
  52. // debug('Failed to remove ' + unlinkedAttachment + 'in gridFS', error);
  53. // });
  54. lib.generateUrl = function (filePath) {
  55. return path.posix.join('/uploads', filePath);
  56. };
  57. return lib;
  58. };