Tips for uploading numerous images to Firebase using React Native Fetch Blob

I have a collection of images stored in an array (image paths are stored in the array). I am trying to upload each image using a for loop, but only the last image gets uploaded. My approach involves using React Native Fetch Blob and Firebase for this task.

for(var i = 0; i < this.state.imagesUri;i++){
 Blob.build(RNFetchBlob.wrap(this.state.imagesUri[i].path),{ type : 'image/jpeg' })
            .then((blob) => firebase.storage()
            .ref("userPhoto").child("image"+i)
            .put(blob, { contentType : 'image/png' }).then(()=>{
   var storage =  firebase.storage().ref("userPhoto/").child("image"+i);
              storage.getDownloadURL().then((url)=>{
                var url = url;
              });
            })
          );
        }

Answer №1

Hopefully this solution proves to be useful

 onSend(images) {
        let photo = images.map( img=> img.image); 
        photo.forEach((image, i) => {
        const sessionId = new Date().getTime();
        const Blob = RNFetchBlob.polyfill.Blob;
        const fs = RNFetchBlob.fs;
        window.XMLHttpRequest =                     
        RNFetchBlob.polyfill.XMLHttpRequest;
        window.Blob = Blob;
        let uploadBlob = null;
        let mime = 'image/jpg';
        const imageRef = this.image.child(`${sessionId}${i}`);
            fs.readFile(image, 'base64')
                                .then((data) => {
                                    return Blob.build(data, { type: `${mime};BASE64` })
                                })
                                .then((blob) => {
                                    uploadBlob = blob;
                                    return imageRef.put(blob, { contentType: mime })
                                })
                                .then(() => {
                                    uploadBlob.close();
                                    return imageRef.getDownloadURL()
                                })
                                .then((url) => {
                                console.log(url)                                        
                               })
                                .catch((error) => {
          
                                });

                              })
                            } 

Answer №2

Alright, to start off with, the key is to store the length of the array in a cache variable called length.

With this change, your for loop will be structured as follows:

for(var i = 0, length = this.state.imagesUri.length; i < length;i++){
. You may have also noticed that there's no longer a need to check if i < this.state.imagesUri (This comparison was incorrect since imagesUri is an array).

Answer №3

This piece of code is designed for the purpose of uploading multiple images using Firebase and 'rn-fetch-blob' in a React Native environment.

const uploadMultipleImages = async (params) => {
  const { imageUrls, mime = 'application/octet-stream', userID, timeStamp } = params;

  const urls = imageUrls.map((url) => {
    const uploadUrl = Platform.OS === 'ios' ? url.replace('file://', '') : url;
    const currentTime = Date.now();
    const imageReference = firebase.storage().ref(`images/${userID}/meal/${timeStamp}`).child(`${currentTime}.png`);
    
    return fs.readFile(uploadUrl, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` });
      })
      .then((blob) => {
        return imageReference.put(blob._ref, blob, { contentType: mime });
      })
      .then(() => {
        return imageReference.getDownloadURL();
      })
      .then((downloadedUrl) => {
        return downloadedUrl;
      })
      .catch((error) => {
        return error.message;
      })
  });

  return Promise.all(urls)
    .then((results) => {
      return results;
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

calls to res.send and res.render

I'm currently trying to determine if it's possible to use res.send(data) and res.render('reports') simultaneously in my code. To provide more details, when I navigate to '/reports', on the server side I am executing a REST ca ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

Using tabs within a Dialog prevents the Dialog from adjusting its height automatically

Solved: Find the solution in the comments section below. I recently built a Tabs feature within a Dialog box, but ran into an issue where the height of the Dialog did not match up with the height of the tab. The problem arose when a form was placed insid ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

Having issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

Developing dynamic objects for input string fields in AngularJS

In my AngularJS view, I have the following setup: <label class="control-label">Name:</label> <input type="text" class="form-control" ng-model="config.name" /> <br /> <label class="control-label">versionSpecificApiConfig:&l ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

Tips for updating process.version in a Node.js environment

After upgrading my node version from v3 to v11 using nvm with the command nvm use 11.12.0, I noticed that when I check the version using node -v in the terminal, it correctly shows 11.12.0. I also have a node js application that is started through pm2. I ...

Conceal a row depending on the value in a specific column

After reviewing the data in the table provided: +-----------------------+-----------------+---------------+ | 212 | fred | red | +-----------------------+-----------------+---------------+ | 230 ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

`Month filter functionality optimized`

I have a flirty plugin installed on my website and it's working great except for one thing: I'd like the month category to be filtered in chronological order instead of alphabetically. Is there a way to achieve this? In simpler terms, how can I ...

Crafting personalized objects from an array

In the process of creating an object from an array, I am faced with a dilemma. The elements in the array are as follows: var arr = [ 'find({ qty: { $lt: 20 } } )', 'limit(5)', 'skip(0)' ] Despite my efforts, my code is ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

Executing jQuery code after a data update in Angular can be achieved by utilizing

Currently, I am working with Angular 1.4.7 on a site that was not set up by me. As a result, I am uncertain about the specific information needed in this scenario. We are displaying search filters, but their enabling or disabling is controlled by data fetc ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...