Last active
October 22, 2021 13:48
-
-
Save efvi/7c9b4464a7c34c8279a341c31b41e2c5 to your computer and use it in GitHub Desktop.
Image upload with AngularJS + Node.js + Firebase
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
// Angular controller | |
$scope.imageUpload = function(event, index) { | |
var files = event.target.files //FileList object | |
for (var i = 0; i < files.length; i++) { | |
var file = files[i] | |
var reader = new FileReader() | |
reader.onload = (function(index){ | |
return function(e) { | |
$scope.$apply(function() { | |
self.picture = e.target.result // I'm uploading this variable that stores the encoded file (base64) | |
}) | |
} | |
})(index) | |
reader.readAsDataURL(file) | |
} | |
} |
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
// Express route running on my Node api | |
const express = require('express') | |
const router = express.Router() | |
const admin = require('firebase-admin') | |
const stream = require('stream') | |
const MyMongoEntity = require('../../model/my-mongo-entity') | |
router.post('/resource', (req, res) => { | |
if(!req.body.field1 || !req.body.field2 || !req.body.field3) { | |
res.status(500).json({ | |
message: 'Malformed body', | |
error: { | |
status: 500 | |
} | |
}) | |
} else { | |
const bucket = admin.storage().bucket('my-awesome-project.appspot.com') | |
let c = new MyMongoEntity(req.body) | |
c.save(err => { | |
if (err) { throw err } | |
let fileB64 = req.body.band.split(';') | |
let mime = fileB64[0].split(':')[1] | |
if(!mime) fileB64[1] = mime = 'image/png' | |
let decodedImage = new Buffer(fileB64[1].substring(7), 'base64') | |
let bufferStream = new stream.PassThrough() | |
bufferStream.end(decodedImage) | |
let file = bucket.file(`my-resource/${c._id}/file.${mime.split('/')[1]}`) | |
bufferStream | |
.pipe(file.createWriteStream({ | |
metadata: { | |
contentType: mime | |
} | |
})) | |
.on('error', err => { | |
throw err | |
}) | |
.on('finish', () => { | |
res.json(c) | |
}) | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment