fileUploader.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * fileUploader
  3. */
  4. module.exports = function(crowi, app) {
  5. 'use strict';
  6. var aws = require('aws-sdk')
  7. , debug = require('debug')('crowi:lib:fileUploader')
  8. , Promise = require('bluebird')
  9. , config = crowi.getConfig()
  10. , lib = {}
  11. ;
  12. function getAwsConfig ()
  13. {
  14. return {
  15. accessKeyId: config.crowi['aws:accessKeyId'],
  16. secretAccessKey: config.crowi['aws:secretAccessKey'],
  17. region: config.crowi['aws:region'],
  18. bucket: config.crowi['aws:bucket']
  19. };
  20. }
  21. function isUploadable(awsConfig) {
  22. if (!awsConfig.accessKeyId ||
  23. !awsConfig.secretAccessKey ||
  24. !awsConfig.region ||
  25. !awsConfig.bucket) {
  26. return false;
  27. }
  28. return true;
  29. }
  30. // lib.deleteFile = function(filePath, callback) {
  31. // // TODO 実装する
  32. // };
  33. //
  34. lib.uploadFile = function(filePath, contentType, fileStream, options) {
  35. var awsConfig = getAwsConfig();
  36. if (!isUploadable(awsConfig)) {
  37. return new Promise.reject(new Error('AWS is not configured.'));
  38. }
  39. aws.config.update({
  40. accessKeyId: awsConfig.accessKeyId,
  41. secretAccessKey: awsConfig.secretAccessKey,
  42. region: awsConfig.region
  43. });
  44. var s3 = new aws.S3();
  45. var params = {Bucket: awsConfig.bucket};
  46. params.ContentType = contentType;
  47. params.Key = filePath;
  48. params.Body = fileStream;
  49. params.ACL = 'public-read';
  50. return new Promise(function(resolve, reject) {
  51. s3.putObject(params, function(err, data) {
  52. if (err) {
  53. return reject(err);
  54. }
  55. return resolve(data);
  56. });
  57. });
  58. };
  59. lib.generateS3FileUrl = function(filePath) {
  60. var awsConfig = getAwsConfig();
  61. var url = 'https://' + awsConfig.bucket +'.s3.amazonaws.com/' + filePath;
  62. return url;
  63. };
  64. return lib;
  65. };