Created
March 5, 2018 08:46
-
-
Save stackdumper/f532881346859b04aa8485bfeb55cfc3 to your computer and use it in GitHub Desktop.
Cloud Functions: Upload image from URL to Cloud Storage.
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
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
const request = require('request').defaults({ encoding: null }); | |
const cors = require('cors')({ origin: true }); | |
admin.initializeApp(functions.config().firebase); | |
const bucket = admin.storage().bucket(); | |
exports.uploadImageByURL = functions.https.onRequest((req, res) => { | |
cors(req, res, () => { | |
request.head(req.query.url, (err, resp, body) => { | |
const filePath = `images/${ shortid() }.${ resp.headers['content-type'].split('/')[1] }`; | |
const writeStreamToBucket = bucket | |
.file(filePath) | |
.createWriteStream() | |
const stream = request(req.query.url).pipe(writeStreamToBucket); | |
stream.on('finish', () => { | |
res | |
.status(200) | |
.json({ filePath }); | |
}); | |
stream.on('error', (e) => { | |
res | |
.status(400) | |
.json(e); | |
}); | |
}); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment