Skip to content
This repository has been archived by the owner on Feb 12, 2021. It is now read-only.

Basic support for upload buffer #154

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down