Skip to content

Instantly share code, notes, and snippets.

@RoySung
Last active November 25, 2019 03:55
Show Gist options
  • Save RoySung/3989b42f7c7c5acddac9bdac544ee827 to your computer and use it in GitHub Desktop.
Save RoySung/3989b42f7c7c5acddac9bdac544ee827 to your computer and use it in GitHub Desktop.
using serverless upload file to s3
'use strict'
const AWS = require('aws-sdk')
const Busboy = require('busboy')
const S3 = new AWS.S3()
const makeResponse = (error, result) => {
const statusCode = error && error.statusCode || 200
return {
statusCode,
headers: {
"Access-Control-Allow-Origin" : "*"
},
body: JSON.stringify(result),
}
}
const upload = (path, file, contentType, callback) => {
const params = {
Bucket: 'activity',
Key: path,
Body: file,
ACL: 'public-read',
ContentType: contentType
}
S3.upload(params, (err, res) => {
if (err) console.error(err, res)
callback(err, res)
})
}
module.exports.upload = (req, context, callback) => {
const { headers } = req
const busboy = new Busboy({ headers })
const uploadData = {
file: null,
path: null,
mimetype: null
}
let formData = {}
busboy.on('field', function(fieldname, value) {
formData[fieldname] = value
})
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', function(data) {
uploadData.file = data
uploadData.contentType = mimetype
})
})
busboy.on('error', () => {
console.error(error)
})
busboy.on('finish', function() {
uploadData.path = formData.path
const { path, file, contentType } = uploadData
upload(path, file, contentType, (error, result) => {
if(error) context
const response = makeResponse(error, result)
context.succeed(response)
})
})
busboy.write(req.body, 'binary')
busboy.end()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment