index.js 1.7 KB

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