Uplaod to Firebase Storage from Node Express REST
I need to upload user profile picture from mobile device trogh rest API to Firebase storage .Finally I go the follwing articale wich really guide me .
In order to upload the file from Express REST I used connect-busboy and fs node modules .
Route file
router.post('/api/user-pic/profile-type/:type', ProfilePicController.setProfile);
Controller File
exports.setProfile = function(req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filename);
file.pipe(fstream);
const filePath = __dirname + '/files/' + filename;
const fileMime = mime.lookup(filename);
const fileExt= mime.extension(fileMime);
////////// FIREBASE UPLOAD CODE /////////////////////////
fstream.on('close', function () {
// remove temp file in server
});
});
});
This will create a file in the server temporary.
Upload to Firebase .
In order to upload files to fire base you need follwing steps to fallow. This was taken from MS MUSE
1.Get a Private Key
in order to call Google Cloud Storage API, we need to get an API Key first. This is quite simple
- from your Firebase application console page go to Project Settings
- open Service Accounts tab and select Firebase Admin SDK
- you should find a Generate Private Key button which will download the API Key as a JSON file.
- copy this file to the root of your Node project
2. install @google-cloud/storage module
As I stated earlier, we will be using google cloud sdk instead of firebase.
npm install @google-cloud/storage --save
3. Setup and call google cloud storage api
In order to setup our code, we need three things.
- Bucket Name: in your Firebase dashboard, navigate to Storage. you should find there a url that looks like this "gs://<your-project-id>.appspot.com". your bucket name is "<your-project-id>.appspot.com"
- ProjectId: this is the <project-id> portion from the bucket name
- keyfilename: this is the name of the file containing the private api key.
We now have everything we need. First setup connection to google cloud storage
JavaScript
const keyFilename="./my-private-api-key-file.json"; //replace this with api key file
const projectId = "my-project-id-should-go-here" //replace with your project id
const bucketName = `${projectId}.appspot.com`;
const gcs = require('@google-cloud/storage')({
projectId,
keyFilename
});
const bucket = gcs.bucket(bucketName);
You are now ready to start managing your Firebase Storage.
File upload code below will be insrted to Contoller file commeted section So ,the temp file will trasfered to cloud. It has used mime node module too.
const uploadTo = 'profile-pics/'+userId+'.'+fileExt;
console.log('upload to '+uploadTo);
bucket.upload(filePath,{
destination:uploadTo,
public:true,
metadata: {contentType: fileMime,cacheControl: "public, max-age=300"}
}, function(err, file) {
if(err)
{
console.log(err);
res.json({
"success":false,
"error":err
});
}
console.log(createPublicFileURL(uploadTo));
});
The follwing function will retun the URL of the picture
function createPublicFileURL(storageName) {
const bucketName = process.env.FIREBASE_PROJECT_ID+'.appspot.com';
return `http://storage.googleapis.com/${bucketName}/${encodeURIComponent(storageName)}`;
}
In addtion to that I had to enable Filrebase rules API for edit storage rules.It will redirected when you go to storage >> Rules tab.
Futher filrebase ask to enable Google Cloud Storage JSON API .Project Settings >> Manage All Service Accounts in Service Accounts tab.
Comments
Post a Comment