local.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const debug = require('debug')('growi:service:fileUploaderLocal');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const mkdir = require('mkdirp');
  5. module.exports = function(crowi) {
  6. 'use strict';
  7. const lib = {};
  8. const basePath = path.posix.join(crowi.publicDir, 'uploads');
  9. function getFilePathOnStorage(attachment) {
  10. if (attachment.filePath != null) { // remains for backward compatibility for v3.3.5 or below
  11. return attachment.filePath;
  12. }
  13. const pageId = attachment.page._id || attachment.page;
  14. const filePath = path.posix.join(basePath, pageId.toString(), attachment.fileName);
  15. return filePath;
  16. }
  17. lib.deleteFile = function(fileId, filePath) {
  18. debug('File deletion: ' + filePath);
  19. return new Promise(function(resolve, reject) {
  20. fs.unlink(path.posix.join(basePath, filePath), function(err) {
  21. if (err) {
  22. return reject(err);
  23. }
  24. resolve();
  25. });
  26. });
  27. };
  28. lib.uploadFile = function(filePath, contentType, fileStream, options) {
  29. debug('File uploading: ' + filePath);
  30. return new Promise(function(resolve, reject) {
  31. var localFilePath = path.posix.join(basePath, filePath)
  32. , dirpath = path.posix.dirname(localFilePath);
  33. mkdir(dirpath, function(err) {
  34. if (err) {
  35. return reject(err);
  36. }
  37. var writer = fs.createWriteStream(localFilePath);
  38. writer.on('error', function(err) {
  39. reject(err);
  40. }).on('finish', function() {
  41. resolve();
  42. });
  43. fileStream.pipe(writer);
  44. });
  45. });
  46. };
  47. /**
  48. * Find data substance
  49. *
  50. * @param {Attachment} attachment
  51. * @return {stream.Readable} readable stream
  52. */
  53. lib.findDeliveryFile = async function(attachment) {
  54. const filePath = getFilePathOnStorage(attachment);
  55. // check file exists
  56. try {
  57. fs.statSync(filePath);
  58. }
  59. catch (err) {
  60. throw new Error(`Any AttachmentFile that relate to the Attachment (${attachment._id.toString()}) does not exist in local fs`);
  61. }
  62. // return stream.Readable
  63. return fs.createReadStream(filePath);
  64. };
  65. /**
  66. * chech storage for fileUpload reaches MONGO_GRIDFS_TOTAL_LIMIT (for gridfs)
  67. */
  68. lib.checkCapacity = async(uploadFileSize) => {
  69. return true;
  70. };
  71. return lib;
  72. };