Created
September 20, 2020 15:54
-
-
Save graphoarty/8c9276cb96d2f09e4bdad27ba06bdcc5 to your computer and use it in GitHub Desktop.
Upload File to S3 from URL (Firebase Functions / 2020)
This file contains 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
const functions = require('firebase-functions'); | |
const AWS = require('aws-sdk'); | |
var https = require('https'); | |
const cors = require('cors')({origin: true}); | |
AWS_ACCESS_KEY = "aws-access-key-goes-here"; | |
AWS_SECRET_KEY = "aws-secret-key-goes-here"; | |
BUCKET_NAME = "bucket-name-goes-here"; | |
const s3 = new AWS.S3({ | |
accessKeyId: AWS_ACCESS_KEY, | |
secretAccessKey: AWS_SECRET_KEY | |
}); | |
exports.main = functions.https.onRequest((req, res) => { | |
cors(req, res, () => { | |
if(req.method === 'POST') { | |
data = req.body; | |
if( | |
data.hasOwnProperty('url') && | |
data.hasOwnProperty('s3_path') | |
) { | |
url = data['url'].toString().replace("http://", "https://"); | |
s3_path = data['s3_path'].toString(); | |
https.get(url, (response) => { | |
const params = { | |
Bucket: BUCKET_NAME, | |
Key: s3_path, | |
Body: response | |
}; | |
s3.upload(params, (err, data) => { | |
if (err) { | |
res.send(JSON.stringify({ | |
'success': false, | |
'message': 'upload_failed' | |
})); | |
} | |
res.send(JSON.stringify({ | |
'success': true, | |
'message': 'file_successfully_uploaded' | |
})); | |
}); | |
}); | |
} else { | |
res.send(JSON.stringify({ | |
'success': false, | |
'message': 'an_error_occured' | |
})); | |
} | |
} else { | |
res.status(204).send(''); | |
} | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment