Created
April 25, 2017 17:30
-
-
Save mattlockyer/d4609c5e87dd0eaef87e08ebe294c04d to your computer and use it in GitHub Desktop.
s3 put and get functions
This file contains hidden or 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
/************************************** | |
* File Put | |
**************************************/ | |
const uuidV1 = require('uuid/v1'); | |
const multer = require('multer'); | |
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10*1024*1024 } }); //10mb limit | |
const fileUpload = (req, res) => { | |
//get args | |
const { id } = req.body; | |
const file = req.file; | |
const fn = file.originalname; | |
const Key = id + '/' + fn + '_uuid_' + uuidV1(); | |
//handle local request | |
if (process.env.LOCAL) { | |
res.send({ res: 'Local Success. Key: ' + Key }); | |
return; | |
} | |
const params = { | |
Key, | |
Bucket: bucketName, | |
Body: file.buffer, | |
}; | |
s3.putObject(params, (err, data) => { | |
if (err) { | |
winston.log('error', err, err.stack); | |
res.send({ res: 'Error Uploading Data: ' + JSON.stringify(err) + '\n' + JSON.stringify(err.stack) }); | |
} else { | |
winston.log('info', 'Successfully uploaded with Key: ', Key); | |
res.send(Key); | |
} | |
}); | |
}; | |
/************************************** | |
* File Get | |
**************************************/ | |
const fileGet = (req, res) => { | |
const { Key } = req.body; | |
//handle local | |
if (process.env.LOCAL) { | |
res.send({ res: 'Local Success. Key: ' + Key }); | |
return; | |
} | |
const params = { | |
Key, | |
Bucket: bucketName, | |
}; | |
const fileStream = s3.getObject(params, (err, data) => { | |
if (err) { | |
winston.log('error', err, err.stack); | |
res.send({ res: 'Error Getting Data: ' + JSON.stringify(err) + '\n' + JSON.stringify(err.stack) }); | |
} else { | |
winston.log('info', 'Successfully got file data', data); | |
res.send(data.Body); | |
} | |
}).createReadStream(); | |
fileStream.pipe(res); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment