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

JavaScript Array failing to transfer to PHP using AJAX

I've encountered a recurring issue with my code and despite searching for solutions, I can't seem to find one that works for me. The problem lies in trying to delete a specific row from a table based on whether the user selects a checkbox associa ...

Arrange the JSON object according to the date value

I am working on a JavaScript project that involves objects. Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"} My goal is to create a new object where the dates are sorted in descending order. Here's an example of what I want: SortedObject ...

Are you in need of a BISON middleware solution for socket.io encoding and decoding?

Is there a method to manipulate the data transmitted by socket.io just before it is sent or received? I was considering implementing something like an express middleware. This way, I could encode the data after the normal .emit() call and before the socket ...

Connecting with a php anchor and hash symbol in a website URL

Looking to include a PHP anchor along with a hash anchor in an HTML link. <?php echo '<a href="test.php?page='.$i.'#hash">'.$i.'</a>'; ?> The PHP code successfully echoes the link, but upon clicking it, th ...

Implementing the fetch API with radio buttons in a React Native application

I found a useful package for radio buttons called react-native-flexi-radio-button. Currently, I'm working on displaying API results within radio buttons. The API response provides 4 options, and my goal is to render text alongside the corresponding ra ...

Initiating the Gmail React component for composing messages

Is it possible to use a React application to open mail.google.com and prefill the compose UI with data? This is a requirement that I need help with. ...

How to update deeply nested subdocuments in Mongoose

I am faced with an issue while attempting to update sub documents using mongoose by utilizing the request.body without explicitly passing the _id of the sub documents. Despite successfully updating, mongoose is deleting the _id from the sub documents. Con ...

Challenges arise when utilizing CSS3 animations in conjunction with transitions triggered by toggling a JavaScript class

Struggling to activate an animation while updating a class using JavaScript for a PhoneGap app. Planning on utilizing -webkit- prefixes for compatibility. However, the animations are currently unresponsive in Chrome during testing, both when applied to th ...

Refresh directive for concealing elements post authentication

Hey everyone, I'm facing a situation where I need to display certain UI elements based on whether a session is active or not. I initially tried using a directive for this purpose, and while it worked well, I encountered an issue where the directives ...

How can I expand and collapse elements using Angular?

I'm looking to implement a collapsible feature. When the user clicks on the "Section Title", I want the corresponding information to collapse or expand. @Component({ selector: 'knowledge-base', template: ` <div *ngFor="let sect ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

React - the method runs correctly when triggered by state changes, but runs twice when the parent component's state changes

As I work on constructing a page that requires data to be initialized upon mounting, updated based on responses from a websocket server triggered by a button click event, and the ability to disable and re-enable the button with a countdown for the user. M ...

What is the best way to send and configure GET information when the characters in a URI surpass 5,000?

Currently, I am utilizing a Laravel blade template. However, I encountered an error in my code when the size of the textarea item is quite large. I'm in search of a solution to resolve this issue. Hey everyone! Can you guide me on how to successfull ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

Guide to effectively retrieving data from S3 and displaying a view at regular intervals of 4 seconds

In my current project, I am working on fetching a file from S3 and utilizing the data within that file to generate a map on a webpage. To achieve this task, I have set up an Express server along with the EJS templating engine for serving and rendering the ...

Setting default values for route parameters in JavaScript

I'm looking to streamline my JavaScript code by simplifying it. It involves passing in 2 route parameters that are then multiplied together. My goal is to assign default values to the parameters if nothing is passed in, such as setting both firstnum ...