diff --git a/lib/index.js b/lib/index.js index 526f5f1..70387a2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -422,6 +422,79 @@ Client.prototype.uploadFile = function(params) { } }; +Client.prototype.uploadBuffer = function(params) { + var self = this; + var uploader = new EventEmitter(); + uploader.progressAmount = 0; + uploader.progressTotal = 0; + uploader.abort = handleAbort; + uploader.getPublicUrl = function() { + return getPublicUrl(s3Params.Bucket, s3Params.Key, self.s3.config.region, self.s3.config.endpoint); + } + uploader.getPublicUrlHttp = function() { + return getPublicUrlHttp(s3Params.Bucket, s3Params.Key, self.s3.config.endpoint); + } + + var buffer = params.buffer; + uploader.progressTotal = buffer.length; + var s3Params = extend({}, params.s3Params); + if (s3Params.ContentType === undefined) { + s3Params.ContentType = params.defaultContentType || 'application/octet-stream'; + } + var fatalError = false; + + startPuttingObject(); + + return uploader; + + function handleError(err) { + if (fatalError) return; + fatalError = true; + uploader.emit('error', err); + } + + function handleAbort() { + fatalError = true; + } + + function startPuttingObject() { + doWithRetry(tryPuttingObject, self.s3RetryCount, self.s3RetryDelay, onPutObjectDone); + + function onPutObjectDone(err, data) { + if (fatalError) return; + if (err) return handleError(err); + uploader.emit('end', data); + } + } + + function tryPuttingObject(cb) { + self.s3Pend.go(function(pendCb) { + if (fatalError) return pendCb(); + var pend = new Pend(); + s3Params.ContentLength = buffer.length; + uploader.progressAmount = 0; + s3Params.Body = buffer; + + self.s3.putObject(s3Params, function(err, data) { + pendCb(); + if (fatalError) return; + if (err) { + cb(err); + return; + } + pend.wait(function() { + if (fatalError) return; + if (cleanETag(data.ETag) !== crypto.createHash('md5').update(buffer).digest('hex')) { + cb(new Error("ETag does not match MD5 checksum")); + return; + } + cb(null, data); + }); + }); + }); + } +}; + Client.prototype.downloadFile = function(params) { var self = this; var downloader = new EventEmitter();