Created
October 23, 2016 19:21
-
-
Save bilashcse/b4cf7a59c37bdfcbeb503a435f6ef926 to your computer and use it in GitHub Desktop.
Amazon S3 file upload using NodeJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var aws = require('aws-sdk'); | |
var promise = require('bluebird'); | |
var fs = promise.promisifyAll(require('fs')); | |
var awsConfig = { | |
region: "aws.region", | |
accessKeyId: "aws.accessKeyId", | |
secretAccessKey: "aws.secretAccessKey", | |
sslEnabled: true | |
}; | |
var s3 = promise.promisifyAll(new aws.S3(awsConfig)); | |
/** | |
* @param {Object} data - required s3 properties regarding object | |
* @param {String} data.path - absolute path of the object, | |
* @param {String} data.name - name define object relative path, example: path/to/object.ext | |
* @param {String} data.mimeType - aws require content type, provide | |
* @param {String} [data.acl] - default permission is private | |
* @param {String} bucketName - cache-control max age in days | |
* @param {Number} [maxAge] - cache-control max age in days | |
* @returns {promise} - checksum | |
*/ | |
function uploadObject(data, bucketName, maxAge){ | |
return fs.readFileAsync(data.path) | |
.then(function(buffer){ | |
if(data.mimeType){ | |
var params = {}; | |
params.Bucket = bucketName; | |
params.Body = buffer; | |
params.Key = data.name; | |
params.ContentType = data.mimeType; | |
params.ACL = data.acl || 'private'; | |
params.StorageClass = 'STANDARD'; | |
if(maxAge) params.CacheControl = 'max-age=' + (3600 * 24 * maxAge); | |
return s3.putObjectAsync(params); | |
} else | |
throw new Error('mime type is mandatory'); | |
}).then(function(checksum){ | |
return checksum; | |
}).catch(function(err){ | |
console.log("Error in CDN file upload, ", data.path, err); | |
return err; | |
}); | |
} | |
module.exports = { | |
uploadObject: uploadObject | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment