Created
October 4, 2018 18:19
-
-
Save elon-gs/d6adae8b77d7c90cb76b591fef10d24a to your computer and use it in GitHub Desktop.
Express backend to upload user-files to Google 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 express = require('express'); | |
const app = express(); | |
const functions = require('firebase-functions'); | |
const cors = require('cors')({ origin: true }); | |
app.use(cors); | |
// upload account image | |
const API_LINK_BASE_URL = 'http://storage.googleapis.com'; | |
const PROJECT_ID = ;// {YOUR_PROJECT_ID, USUALLY A SINGLE WORD}; | |
const BUCKET_ID = ;// {YOUR_BUCKET_ID, E.G. PROJECT_ID.appspot.com}; | |
const Busboy = require('busboy'); | |
const shortid = require('shortid'); | |
app.post('/upload', (req, res) => { | |
const { Storage } = require('@google-cloud/storage'); | |
const storage = new Storage({ | |
projectId: PROJECT_ID | |
}); | |
const bucket = storage.bucket(BUCKET_ID); | |
const busboy = new Busboy({ headers: req.headers }); | |
const fields = {}; | |
const fileUrls = []; | |
busboy.on('field', (fieldname, val) => { | |
console.log(`Processed field ${fieldname}: ${val}.`); | |
fields[fieldname] = val; | |
}); | |
busboy.on('file', (fieldname, uploadedFile, filename) => { | |
console.log(`Processed file ${filename}`); | |
const gcsname = `img_${shortid.generate()}${filename.substr(filename.lastIndexOf('.'))}`; | |
fileUrls.push(`${API_LINK_BASE_URL}/${BUCKET_ID}/${gcsname}`); | |
const gcsfile = bucket.file(gcsname); | |
const writeStream = gcsfile.createWriteStream({ | |
resumable: false | |
}); | |
uploadedFile.pipe(writeStream); | |
return new Promise((resolve, reject) => { | |
uploadedFile.on('end', () => { | |
writeStream.end(); | |
}); | |
writeStream.on('finish', () => { | |
console.log('file finished'); | |
return resolve(); | |
}); | |
writeStream.on('error', reject); | |
}).then(() => { | |
console.log(gcsname); | |
return gcsfile.makePublic(); | |
}).catch(e => res.status(400).send({ error: e })); | |
}); | |
busboy.on('finish', () => { | |
console.log('busboy finished'); | |
return res.status(200).send(fileUrls); | |
}); | |
busboy.end(req.rawBody); | |
}); | |
exports.api = functions.https.onRequest(app); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment