Issue with Firebase Storage: Invalid character detected in the string format 'base64'

I am currently developing a project using react-native and I am facing an issue with uploading an image to Firebase using Firebase Storage. To select the image from the phone, I am utilizing react-native-image-picker, which provides me with the base64 encoded data.

However, when attempting to upload the image to Firebase, I encounter the error message

Firebase Storage: String does not match format 'base64': Invalid character found
, despite verifying that the string is indeed a valid base64 string using regex.

Although I have researched several solutions, none seem to resolve the issue. Here is the code I am using:

function uploadImage(image){
  const user = getCurrentUser();
  const refImage = app.storage().ref(`profileImages/${user.uid}`);

  refImage.putString(image, 'base64').then(() => {
    console.log('Image uploaded');
  });
}

This is how I implement the image picker:

ImagePicker.showImagePicker(ImageOptions, (response) => {
  if (response.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    uploadImage(response.data);
  }
});

Answer №1

in case picture represents a base64 data URL, you have the option to utilize the 'data_url' parameter along with metadata:

function storePicture(picture){
  const user = getCurrentUser();
  const imageRef = app.storage().ref(`userImages/${user.uid}`);

  imageRef.putString(picture, 'data_url', {contentType: 'image/png'}).then(() => {
    console.log('Picture stored successfully');
  });
}

Answer №2

To modify your image variable, simply remove the specified string "data:image/jpeg;base64,. You should retain only the data portion.

Answer №3

Extracting Substring from Image

function uploadProfileImage(image){
      const user = getCurrentUser();
      const refImage = app.storage().ref(`profileImages/${user.uid}`);

      refImage.putString(image.substring(23), 'base64').then(() => {
        console.log('Profile image uploaded successfully');
      });
    }

Answer №4

I utilize the split() method.

function uploadPhoto(photo){
  const user = retrieveCurrentUser();
  const photoRef = app.storage().ref(`userPhotos/${user.uid}`);

  photoRef.putString(photo.split(',')[1], 'base64').then(() => {
    console.log('Photo successfully uploaded');
  });
}

Answer №5

Instead of utilizing the firebase/storage API, I opted to use a Google bucket URL and the expo-file-system package to transfer images or videos from a mobile device to Firebase. Below is the code I employed:

const sendPhotoOrVideo = () => {
    FileSystem.uploadAsync(
      'https://storage.googleapis.com/upload/storage/v1/b/YOUR_BUCKET_NAME/o?uploadType=media&name=FILE_NAME',
      'FILE_LOCATION',
      {
        headers: {
          Authorization:
            'Bearer YOUR_OAUTH2_TOKEN',
        },
      },
    )
}

The FileSystem.uploadAsync function is sourced from the expo-file-system package, while the 'FILE_LOCATION' is obtained using the expo-image-picker package.

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

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Is there a way to control the playback of a video, such as

Currently, I am involved in a project related to IPTV. One of my objectives is to be able to capture the moment at which a video is paused so that when clicking on another button, a small iframe opens with the same video continuing from where it was origin ...

Nuxtjs is functioning properly on 127.0.0.1:5000, but unfortunately it is not working on localhost:5000

Currently, I'm working on a project with Nuxtjs. The application opens successfully when I use the URL 127.0.0.1. However, when I attempt to access it through localhost:5000, I receive the error message Access to localhost was denied. You don't h ...

What is the most effective method for informing the browser about changes in the database?

I've been working with django for about 6 months now and it has been effective for the websites I create. However, I recently encountered an issue while developing a website where users receive notifications whenever another user updates a blog post. ...

Guidelines for accessing an ArrayList containing objects returned by a method within a JAR file

I've encountered an issue where a JAR file I imported into my project has a method that returns an ArrayList. I've defined an object with the same definition in my project, but I'm receiving a type mismatch error. My question is how can I a ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

What is the significance of the underscore prefix in package.json properties?

Can you explain the significance of prefixing properties with an underscore in package.json? What is the reason behind using underscores in this context? "_from": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b190e0a081 ...

What is the best way to access Firebase data within a Vue component?

I can view the data in the Vue console, but there's an issue showing up: 'Property or method "rsvp" is not defined on the instance but referenced during render.' What is the correct way to reference the firebase data? <template> ...

Looking to create a GitHub example in Fiddle but running into issues with getting the result?

I've been working on an example on Fiddle, but it's not functioning as expected. I want to implement i18next so that the text changes when the user switches languages. After searching for a solution, I came across this GitHub repository: https:// ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

How can certain HTML be redirected or hidden for users on mobile devices?

Lately, I've been putting the final touches on my website to present to potential employers as I will soon be starting my job search after graduation. I recently added an "about" section with parallax scrolling effect, but unfortunately, it's not ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

Looping a track on Android

Can someone assist me in setting up a loop to repeat a song every minute? I need the song to play, then after it finishes, wait for a minute before starting again. Any help would be greatly appreciated. final Handler handler = new Handler(); Tim ...

Ways to set the initial value of an input[range] in Angular2 when the value exceeds 100

After encountering a similar issue with AngularJS, I posted a question on StackOverflow titled How to initialize the value of an input[range] using AngularJS when value is over 100. As I dive into learning Angular2, I am curious if it handles initializatio ...

What is the best way to pass parameters in jQuery using .on()?

Hello there, I have a slight dilemma :) Could you please advise me on how to pass a parameter to an external JavaScript function using the .on method? Here is the code snippet: <script> var attachedPo = 0; $this.ready(function(){ $ ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

What is the process for creating custom event bindings in AngularJS?

There is a custom event called core-transitionend (specifically triggered by Polymer), and I am able to specify an event handler using document.addEventListener(). However, what would be the most recommended approach for achieving this in AngularJS? Alter ...