index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // crowi-fileupload-local
  2. module.exports = function(crowi) {
  3. 'use strict';
  4. var debug = require('debug')('growi:lib:fileUploaderLocal')
  5. , fs = require('fs')
  6. , path = require('path')
  7. , mkdir = require('mkdirp')
  8. , lib = {}
  9. , basePath = path.posix.join(crowi.publicDir, 'uploads'); // TODO: to configurable
  10. lib.deleteFile = function(fileId, filePath) {
  11. debug('File deletion: ' + filePath);
  12. return new Promise(function(resolve, reject) {
  13. fs.unlink(path.posix.join(basePath, filePath), function(err) {
  14. if (err) {
  15. return reject(err);
  16. }
  17. resolve();
  18. });
  19. });
  20. };
  21. lib.uploadFile = function(filePath, contentType, fileStream, options) {
  22. debug('File uploading: ' + filePath);
  23. return new Promise(function(resolve, reject) {
  24. var localFilePath = path.posix.join(basePath, filePath)
  25. , dirpath = path.posix.dirname(localFilePath);
  26. mkdir(dirpath, function(err) {
  27. if (err) {
  28. return reject(err);
  29. }
  30. var writer = fs.createWriteStream(localFilePath);
  31. writer.on('error', function(err) {
  32. reject(err);
  33. }).on('finish', function() {
  34. resolve();
  35. });
  36. fileStream.pipe(writer);
  37. });
  38. });
  39. };
  40. lib.generateUrl = function(filePath) {
  41. return path.posix.join('/uploads', filePath);
  42. };
  43. lib.findDeliveryFile = function(fileId, filePath) {
  44. return Promise.resolve(lib.generateUrl(filePath));
  45. };
  46. return lib;
  47. };