Skip to content

Instantly share code, notes, and snippets.

@briansalvattore
Last active March 12, 2019 15:31
Show Gist options
  • Save briansalvattore/e59ec7261b1ae80a52a4afcbb472c808 to your computer and use it in GitHub Desktop.
Save briansalvattore/e59ec7261b1ae80a52a4afcbb472c808 to your computer and use it in GitHub Desktop.
*For this example we are using express
'use strict'
const utils = require('utils')
//...
app.post('/upload/image', (req, res) {
utils.uploadFile(req, 'your bucket', 'your folder',
(downloadUrl) => {
return res.status(201).json({ success: true, downloadUrl: downloadUrl })
},
(err) => {
return res.status(500).json({ success: false, error: err })
}
)
})
'use strict'
const Busboy = require('busboy')
const path = require('path')
const os = require('os')
const fs = require('fs')
const mkdirp = require('mkdirp-promise')
const Storage = require('@google-cloud/storage')
exports.uploadFile = function (req, bucket, folderToSave, onSuccess, onError) {
const busboy = new Busboy({ headers: req.headers })
busboy.on('file', async (fieldname, file, filename) => {
const tempLocalFile = path.join(os.tmpdir(), '/outputFiles/' + filename)
const tempLocalDir = path.dirname(tempLocalFile)
await mkdirp(tempLocalDir)
const writeStream = fs.createWriteStream(tempLocalFile)
file.pipe(writeStream)
file.on('end', () => writeStream.end())
writeStream.on('finish', async () => {
var data = await new Storage()
.bucket(bucket)
.upload(tempLocalFile, { destination: folderToSave + '/' + filename })
var file = data[0]
var downloadUrl = "https://firebasestorage.googleapis.com/v0/b/" + file.bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media"
onSuccess(downloadUrl)
})
writeStream.on('error', (err) => onError(err))
})
busboy.end(req.rawBody)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment