/firebase-tutorials

How to store images in Firebase storage?

Discover a step-by-step guide to storing images in Firebase Storage. Learn project setup, app configuration, image upload, and proper permission handling.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to store images in Firebase storage?

 

Step 1: Set up Firebase Project

 

  • Go to Firebase Console and create a new project.
  • Add a new app to your Firebase project (iOS/Android/Web) depending on your requirements.

 

Step 2: Configure Firebase in Your Application

 

  • For a web app, directly include Firebase SDK links in the HTML file:
<!-- Firebase App (the core Firebase SDK) is always required -->
<script src="https://www.gstatic.com/firebasejs/9.19.1/firebase-app.js"></script>

<!-- Include Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/9.19.1/firebase-storage.js"></script>
  • For Android apps, add Firebase dependencies in build.gradle:
// In your top-level build.gradle file
buildscript {
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.3.10' // Check for latest version
    }
}
// In your app-level build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
    // ...
    implementation 'com.google.firebase:firebase-storage:20.0.2' // Check for latest version
}

 

Step 3: Initialize Firebase in Your Application

 

  • For a web app, initialize Firebase in your JavaScript:
// Your web app's Firebase configuration
const firebaseConfig = {
// Your firebase configuration
};

// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
  • For Android apps, initialize Firebase in onCreate() of your MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initialize Firebase
    FirebaseApp.initializeApp(this);
}

 

Step 4: Create Firebase Storage References

 

  • For both web and Android, you need to create a storage reference.

For a web app:

// Create a root reference
const storage = firebase.storage();
const storageRef = storage.ref();

For Android:

// Create a storage reference from our app
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();

 

Step 5: Upload Image

 

For a web app:

const fileInput = document.querySelector('#file');
fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  const uploadTask = storageRef.child(`images/${file.name}`).put(file);

  uploadTask.on('state_changed', 
    (snapshot) => {
      // Observe state change events such as progress
      // Handle state changes for progress
    }, 
    (error) => {
      // Handle unsuccessful uploads
      console.error('Upload failed:', error);
    }, 
    () => {
      // Handle successful uploads on complete
      console.log('Upload successful!');
    }
  );
});

For Android:

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/" + file.getLastPathSegment());
riversRef.putFile(file)
    .addOnSuccessListener(taskSnapshot -> {
        // Handle successful uploads on complete
        Log.d(TAG, "Upload successful");
    })
    .addOnFailureListener(e -> {
        // Handle unsuccessful uploads
        Log.w(TAG, "Upload failed", e);
    });

 

Step 6: Handling Permissions (Android Only)

 

  • Ensure you have the necessary permissions in AndroidManifest.xml for accessing storage:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • Don't forget to request permissions at runtime if targeting APIs above 23:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, 
          new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
          REQUEST_CODE);
}

 

Step 7: Enable Firebase Storage Rules

 

  • Go to Firebase Console > Storage > Rules.
  • Set rules to:
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null; // Requires authentication
    }
  }
}

With this, you should be able to upload images to Firebase Storage securely and efficiently. Always test your integration thoroughly to ensure all flows (success and error) are handled correctly.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022