diff options
| author | Jules Laplace <jules@okfoc.us> | 2016-11-14 11:49:32 -0500 |
|---|---|---|
| committer | Jules Laplace <jules@okfoc.us> | 2016-11-14 11:49:32 -0500 |
| commit | 4d6690ccc48266e7755829d32bf0440177d8c391 (patch) | |
| tree | c7f895f65316c8853bf7a916320b32be5bb45e2a /lib/upload.js | |
initial stuff
Diffstat (limited to 'lib/upload.js')
| -rw-r--r-- | lib/upload.js | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/lib/upload.js b/lib/upload.js new file mode 100644 index 0000000..62ed9de --- /dev/null +++ b/lib/upload.js @@ -0,0 +1,66 @@ + +var crypto = require('crypto') +var knox = require('knox') + +var s3 = module.exports.s3 = knox.createClient({ + key: process.env.S3_KEY, + secret: process.env.S3_SECRET, + bucket: process.env.S3_BUCKET, +}); + +var acceptableuploadTypes = { + 'image/gif': 'gif', + 'image/jpeg': 'jpg', + 'image/png': 'png' +} + +module.exports.put = function (key, file, opt) { + var fileSize, fileType, filename + var err + var now = new Date() + + var extension = acceptableuploadTypes[file.mimetype] + filename = crypto.createHash('md5').update(file.buffer).digest('hex') + "." + extension; + + var remote_path = process.env.S3_DIR + filename + + if (! extension) { + err = "Unacceptable filetype" + } + else if (file.size < 10) { + err = "File too small" + } + else if (file.size > 2097152) { // 2mb limit + err = "File too large. Uploads can be a maximum of 2 mb." + } + + if (err) { + console.error(">>>", err) + opt.unacceptable && opt.unacceptable(err) + return + } + + opt.acceptable && opt.acceptable(err) + + console.log("upload > ", remote_path) + s3.putBuffer(file.buffer, remote_path, { + 'Content-Length': file.size, + 'Content-Type': file.mimetype, + 'x-amz-acl': 'public-read', + }, function(err, s3res) { + if (err || s3res.statusCode !== 200) { + console.error(s3res.statusCode, err) + if (s3res && s3res.resume) { + s3res.resume() + } + return + } + + var file_url = s3res.url || s3res.req.url + + opt.success && opt.success(file_url) + }).on('error', function(err, s3res){ + console.error("error", err) + s3res && s3res.resume && s3res.resume() + }) +} |
