Skip to content

Instantly share code, notes, and snippets.

@graphoarty
Created September 20, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphoarty/8c9276cb96d2f09e4bdad27ba06bdcc5 to your computer and use it in GitHub Desktop.
Save graphoarty/8c9276cb96d2f09e4bdad27ba06bdcc5 to your computer and use it in GitHub Desktop.
Upload File to S3 from URL (Firebase Functions / 2020)
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