index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. , Promise = require('bluebird')
  9. , Config = crowi.model('Config')
  10. , config = crowi.getConfig()
  11. , lib = {}
  12. , basePath = path.join(crowi.publicDir, 'uploads'); // TODO: to configurable
  13. lib.deleteFile = function(filePath) {
  14. debug('File deletion: ' + filePath);
  15. return new Promise(function(resolve, reject) {
  16. fs.unlink(path.join(basePath, filePath), function(err) {
  17. if (err) {
  18. debug(err);
  19. return reject(err);
  20. }
  21. resolve();
  22. });
  23. });
  24. };
  25. lib.uploadFile = function(filePath, contentType, fileStream, options) {
  26. debug('File uploading: ' + filePath);
  27. return new Promise(function(resolve, reject) {
  28. var localFilePath = path.join(basePath, filePath)
  29. , dirpath = path.dirname(localFilePath);
  30. mkdir(dirpath, function(err) {
  31. if (err) {
  32. return reject(err);
  33. }
  34. var writer = fs.createWriteStream(localFilePath);
  35. writer.on('error', function(err) {
  36. reject(err);
  37. }).on('finish', function() {
  38. resolve();
  39. });
  40. fileStream.pipe(writer);
  41. });
  42. });
  43. };
  44. lib.generateUrl = function(filePath) {
  45. return path.join('/uploads', filePath);
  46. };
  47. return lib;
  48. };