index.js 1.7 KB

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