index.js 1.6 KB

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