How to Upload a File With Axios Firebase

Oh god, the documentation is crazy. Allow me relieve yous some time!

Let me tell y'all, the Firebase documentation is something special. It appears to be so elementary and straightforward only actually, you need to chase down the ends of the earth for those tiny things to make information technology work. But here nosotros go. Let'southward practise this! :-)

Pace 1: Create a Google Deject application

Psst don't worry about billing. It volition all exist FREE under the Spark plan.

Step 2: On the left-hand side of Firebase, click Storage and Get Started.

Gear up up your new Cloud Storage Bucket in a specified region.

Once y'all're all set it should similar this, of course empty with no files. :(

Footstep 3: Navigate to the rules tab and allow public write access.

The saucepan will not allow unauthenticated users to upload to information technology, nosotros can change this past changing the rules.

And then in the rules tab, update the rules to the post-obit:

          rules_version = 'ii';
service firebase.storage {
match /b/{saucepan}/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}

Step 4: Register your web app and take hold of your firebase credentials

Click the </> web icon to get started.

Copy these for afterwards use. Nosotros volition utilise these to connect to your Firebase. Do not share or publish these on your repositories.

Pace v: Create a Node.js Limited app with Firebase

  • We will create a Node.js backend with Express to power our API
  • You'll likely demand Multer (or an culling middleware) to grab the file from the form data in your front end
  • Yous will need to set Firebase and Cloud Storage in your project
  • Yous will demand to install the post-obit packages as dependencies in your project, then npm install these bad boys:
          @google-deject/storage": "^5.8.v",
"body-parser": "^i.19.0",
"cors": "^2.viii.v",
"dotenv": "^ten.0.0",
"limited": "^iv.17.one",
"express-fileupload": "^1.two.ane",
"firebase": "^8.vi.8",
"firebase-admin": "^9.10.0",
"multer": "^1.4.2",
"xhr2": "^0.two.1"

For the Firebase setup, nosotros will demand to grab the Firebase configuration from Step four.

In a config.js file you lot tin can export the Firebase config. Grab the firebase keys from Step 4 and identify them in here. The better way to practice this is from an .env file using process.env (or you tin can paste them in here directly — but that's a bad practice if you are publishing this anywhere..)

          const {
API_KEY,
AUTH_DOMAIN,
DATABASE_URL,
PROJECT_ID,
STORAGE_BUCKET,
MESSAGING_SENDER_ID,
APP_ID,
} = process.env;
module.exports = {
firebaseConfig: {
apiKey: API_KEY,
authDomain: AUTH_DOMAIN,
projectId: PROJECT_ID,
databaseURL: DATABASE_URL,
storageBucket: STORAGE_BUCKET,
messagingSenderId: MESSAGING_SENDER_ID,
appId: APP_ID
}
}

Then we tin can create a db.js file to initialize our Firebase app with the configuration imported from our config file.

          // Requiring firebase (as our db)
const firebase = require('firebase');
// Importing our configuration to initialize our app
const config = crave('./config');
// Creates and initializes a Firebase app instance. Laissez passer options as param
const db = firebase.initializeApp(config.firebaseConfig);
module.exports = db;

At present we tin can use Firebase in other parts of our app, by doing something like this

                      const firebase = require('../db'); // reference to our db                  

And so in your index.js file, let's configure our express app with the basic configurations and prepare one route in our RestAPI.

          'use strict';          const express = require('limited');
const cors = crave('cors');
const imageRoute = require('./routes/image-route');
// import our current configuration
const config = require('./config');
// prepare our app using express
const app = express();
// express setup
app.use(express.json());
app.utilize(cors());
app.use(express.urlencoded({ extended: true }));
// routes (for uploading images to storage)
app.employ('/api', imageRoute.routes)
app.heed(config.port, () => {
console.log ("app is listening on port:", config.port);
})

You'll need to specify a POST road to upload the image. You will also demand to configure Multer as a middleware in your request to brand the file available for you.

For example, in a image-route.js file:

          const express = require('express');
const multer = require('multer');
const {
addImage
} = require('../controllers/imagesController');
const router = limited.Router(); // Setting up multer as a middleware to grab photo uploads
const storage = multer.memoryStorage();
const upload = multer({ storage: storage }).single('file');
// Postal service - Add together Prototype to Cloud Storage
router.post('/upload', upload, addImage);
module.exports = { routes: router }

And then in your controller.js file, you lot would actually update the storage and return the download URL if it is successful.

  • First yous require Firebase and firebase storage
  • You create a reference to the storage using firebase.storage().ref()
  • You create a reference to using the file name (as a preliminary stride)
  • You upload the file buffer into that reference (that actually uploads it to google cloud)
  • Y'all get the download URL using getDownloadURL();
                      const firebase = require('../db');  // reference to our db                                const firestore = firebase.firestore(); // if using firestore                      require("firebase/storage"); // must be required for this to piece of work                                const storage = firebase.storage().ref(); // create a reference to storage                                global.XMLHttpRequest = crave("xhr2"); // must be used to avert bug                    // Add Image to Storage and return the file path
const addImage = async (req, res) => {
endeavour {
// Grab the file
const file = req.file;
// Format the filename
const timestamp = Date.now();
const proper noun = file.originalname.carve up(".")[0];
const blazon = file.originalname.carve up(".")[1];
const fileName = `${name}_${timestamp}.${type}`;
// Step 1. Create reference for file proper noun in cloud storage
const imageRef = storage.kid(fileName);
// Stride ii. Upload the file in the bucket storage
const snapshot = wait imageRef.put(file.buffer);
// Step three. Catch the public url
const downloadURL = await snapshot.ref.getDownloadURL();

res.send(downloadURL);
} catch (error) {
console.log (error)
res.status(400).send(error.message);
}
}
module.exports = {
addImage
}

And that should be all you demand! Hopefully, that was helpful. For farther reading, please see the official documentation:

https://firebase.google.com/docs/storage/spider web/upload-files#spider web-v8_1

Oh and in example you were wondering what a forepart terminate client API call would expect similar, here's an case using Axios:

          // Uploads a single photo to the DB, returns imageURL
const uploadPhoto = async(photo) => {
const imageUploadAPIUrl = `${process.env.REACT_APP_API_SERVER}/api/upload`
const formData = new FormData();
let imageUrl = '';
formData.append('file', photo);
try {
const response = await axios.post(imageUploadAPIUrl, formData);
imageUrl = response.information;
} catch(fault) {
console.error (error);
}
return imageUrl;
}

More content at plainenglish.io

adamssomprood.blogspot.com

Source: https://javascript.plainenglish.io/uploading-an-image-to-firebase-cloud-storage-and-returning-url-with-express-nodejs-713daac7a5d4

0 Response to "How to Upload a File With Axios Firebase"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel