React-native-firebase: Firebase Storage Error: An unknown error has occurred.

Created on 19 May 2018  路  33Comments  路  Source: invertase/react-native-firebase

I using react-native-image-picker for image selection tool to get the file path for putFile() function. But get an error Error: An unknown error has occurred. after I selected the image while uploading.

ImagePicker.showImagePicker(options, (response) => {
  console.log(JSON.stringify(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 {
    firebase.storage().ref("123.jpg").putFile(response.path).then((success) =>{
      console.log(success);
    })
    .catch((error)=>{
      console.log(error);
    })
  }
});

The response json from picker :

{
  "height": 464,
  "width": 825,
  "type": "image/jpeg",
  "fileName": "deadpool-2-domino-cable.jpg",
  "fileSize": 114189,
  "path": "/storage/emulated/0/Download/deadpool-2-domino-cable.jpg",
  "data": "thisisbase64string",
  "uri": "content://media/external/images/media/301465",
  "isVertical": true,
  "originalRotation": 0
}

Environment

  1. Application Target Platform:

Android

  1. Development Operating System:

WIndows 10

  1. React Native version:

0.55.1

  1. RNFirebase Version:

    ^4.0.7

  2. Firebase Module:

Firebase Storage

Android Storage Waiting for User Response

Most helpful comment

I don't know why, but the unknown error from react-native-firebase storage was that it could not find the image on the phone with the given URI path from Image-Picker response json. Instead of using URI I used the path from Image-Picker response json and insert into .putFile(). Hopefully that works for anyone who's still having this issue. Works only for android, use URI for iOS.

The path should look like this: /storage/emulated/0/DCIM/Camera/IMG_20190621_194603.jpg

Response json from Image Picker:
image

All 33 comments

anyone can help please ?

Android? iOS? Please fill out the issue template as it allows us to help you more easily.

Regardless, you need to check your native logs to see if any errors are reported there.

@chrisbianca I have updated the question , it just have an error Error: An unknown error has occurred , other than that everything go fine. Before that it work, few days later, I tried to putFile() again then error coming out.

Try prefixing the path with: file://

@chrisbianca Hi, thanks for you reply, did you mean file://storage/emulated/0/Download/deadpool-2-domino-cable.jpg like this ?

Yes, or alternatively try using the resource.uri value: content://media/external/images/media/301465

@chrisbianca OK , will try and let you know if the Error is still exists , Thanks

@JayricMok how did you get on?

I'm having this same error with iOS storage upload. Unknown error and the data saved in Firebase storage is just JSON data about the file instead of the file itself.

In my case the rules prevented storage access, yet it's an "unknown error"

For my case it is not a permission issue. I changed the rules to Public (allow read, write;) and it still fails with "Unknown error".

Try checking out native logs to see if it gives an indication of what native error is showing.

Found it, in my case at least. The URI of the image from the ImagePicker had a % character in it from the local app cache. This percent was being URI encoded to '%25' which resulted in the file not being found by the putFile code. Adding a decodeURI call around the uri fixed the issue.

let fileUri = decodeURI(pickerResult.uri)

Closing this one due to lack of response - I'd suggest checking the path returned is correct and doesn't contain inconsistent data as per dethells response. If you still have no luck, we'll reopen and help investigate further.

Hi, I'm having the same issue when uploading images from iOS.

I'm using RNF 4.3.6

No problem uploading from Library, but when I take a picture with the camera and then upload I get:

Error: An unknown error has occurred.
    at createErrorFromErrorData (NativeModules.js:121)
    at NativeModules.js:78
    at MessageQueue.__invokeCallback (MessageQueue.js:398)
    at MessageQueue.js:137
    at MessageQueue.__guardSafe (MessageQueue.js:314)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:136)
    at debuggerWorker.js:70

I am also resizing the images using react-native-image-resizer but have tried uploading without resize too and that did not work either so I guess the problem is somewhere else...
This is my code:

ImagePicker.showImagePicker(options, (pickerRes) => {
      console.log('Response = ', pickerRes);

      if (pickerRes.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (pickerRes.error) {
        console.log('ImagePicker Error: ', pickerRes.error);
      }
      else {
        let source = { uri: pickerRes.uri };
        console.log(source);

        this.state.user.profile_picture = 'data:image/jpeg;base64,' + pickerRes.data
        this.setState({ user: this.state.user });

        const fileName = pickerRes.fileName

        var width = pickerRes.width
        var height = pickerRes.height

        console.log('old:', width, 'x', height)

        const finalSize = 100 // the final size of a resized image. 200x400 would become 100x200

        if (width > 100 && height > 100) {
          var coef;
          if (width > height) {
            coef = height/finalSize
          } else {
            coef = width/finalSize
          }
          width = Math.floor(width/coef)
          height = Math.floor(height/coef)
        }

        console.log('new:', width, 'x', height)

        ImageResizer.createResizedImage(pickerRes.uri, width, height, 'JPEG', 100)
          .then((resizeRes) => {
            firebase
              .storage()
              .ref(fileName)
              .putFile(
                resizeRes.uri
              )
              .then(storageRes => {
                this.usersRef.doc(this.state.user._id).update({ profile_picture: storageRes.downloadURL})
              })
              .catch(err => { console.log('error uploading to bucket:', err) });

          }).catch((err) => {
            console.log('error resizing image:', err);
          });

      }
    })

  }

Just tried on Android and it works fine so its really a iOS problem.
Here is the native log from XCode:

2018-09-10 20:13:50.390 [info][tid:com.facebook.react.JavaScript] 'error uploading to bucket:', { [Error: An unknown error has occurred.]
  framesToPop: 1,
  code: 'storage/unknown',
  nativeStackIOS: 
   [ '0   YetnoApp                            0x00000001011b820c RCTJSErrorFromCodeMessageAndNSError + 152',
     '1   YetnoApp                            0x0000000101151d04 __41-[RCTModuleMethod processMethodSignature]_block_invoke_2.218 + 176',
     '2   YetnoApp                            0x0000000101387d78 -[RNFirebaseStorage promiseRejectStorageException:error:] + 1120',
     '3   YetnoApp                            0x00000001013861c0 __74-[RNFirebaseStorage addUploadObservers:uploadTask:path:resolver:rejecter:]_block_invoke.492 + 188',
     '4   YetnoApp                            0x0000000100bba398 __50-[FIRStorageObservableTask fireHandlers:snapshot:]_block_invoke_2 + 56',
     '5   libdispatch.dylib                   0x00000001026951dc _dispatch_call_block_and_release + 24',
     '6   libdispatch.dylib                   0x000000010269519c _dispatch_client_callout + 16',
     '7   libdispatch.dylib                   0x0000000102699d2c _dispatch_main_queue_callback_4CF + 1180',
     '8   CoreFoundation                      0x00000001838f3070 <redacted> + 12',
     '9   CoreFoundation                      0x00000001838f0bc8 <redacted> + 2272',
     '10  CoreFoundation                      0x0000000183810da8 CFRunLoopRunSpecific + 552',
     '11  GraphicsServices                    0x00000001857f6020 GSEventRunModal + 100',
     '12  UIKit                               0x000000018d830758 UIApplicationMain + 236',
     '13  YetnoApp                            0x000000010077c2a4 main + 124',
     '14  libdyld.dylib                       0x00000001832a1fc0 <redacted> + 4' ],
  userInfo: null,
  domain: 'RCTErrorDomain',
  line: 2054,
  column: 26,
  sourceURL: 'http://192.168.2.105:8081/index.bundle?platform=ios&dev=true&minify=false' }
2018-09-10 20:13:50.402139+0200 YetnoApp[4881:3038984] 'error uploading to bucket:', { [Error: An unknown error has occurred.]
  framesToPop: 1,
  code: 'storage/unknown',
  nativeStackIOS: 
   [ '0   YetnoApp                            0x00000001011b820c RCTJSErrorFromCodeMessageAndNSError + 152',
     '1   YetnoApp                            0x0000000101151d04 __41-[RCTModuleMethod processMethodSignature]_block_invoke_2.218 + 176',
     '2   YetnoApp                            0x0000000101387d78 -[RNFirebaseStorage promiseRejectStorageException:error:] + 1120',
     '3   YetnoApp                            0x00000001013861c0 __74-[RNFirebaseStorage addUploadObservers:uploadTask:path:resolver:rejecter:]_block_invoke.492 + 188',
     '4   YetnoApp                            0x0000000100bba398 __50-[FIRStorageObservableTask fireHandlers:snapshot:]_block_invoke_2 + 56',
     '5   libdispatch.dylib                   0x00000001026951dc _dispatch_call_block_and_release + 24',
     '6   libdispatch.dylib                   0x000000010269519c _dispatch_client_callout + 16',
     '7   libdispatch.dylib                   0x0000000102699d2c _dispatch_main_queue_callback_4CF + 1180',
     '8   CoreFoundation                      0x00000001838f3070 <redacted> + 12',
     '9   CoreFoundation                      0x00000001838f0bc8 <redacted> + 2272',
     '10  CoreFoundation                      0x0000000183810da8 CFRunLoopRunSpecific + 552',
     '11  GraphicsServices                    0x00000001857f6020 GSEventRunModal + 100',
     '12  UIKit                               0x000000018d830758 UIApplicationMain + 236',
     '13  YetnoApp                            0x000000010077c2a4 main + 124',
     '14  libdyld.dylib                       0x00000001832a1fc0 <redacted> + 4' ],
  userInfo: null,
  domain: 'RCTErrorDomain',
  line: 2054,
  column: 26,
  sourceURL: 'http://192.168.2.105:8081/index.bundle?platform=ios&dev=true&minify=false' }

+1 Stuck now. Was working fine with the FirebaseJS lib and blobs. Now doesn't work any alternative. String / Blob / Uri, nadda.

Hi, I'm having the same issue when uploading images from Android.

`     [upload = () => {
     Firebase.storage().ref('images/' + new Date().getTime()).putFile(this.state.uri)

      .then(({downloadURL}) =>

        Firebase.database()

        .ref("images/" + new Date().getTime())

        .set({

          downloadURL

        })

      )
 .then(() => alert('Uploaded')).catch(e => {

      console.log(e);

      alert("Error");
    });

};

`

The response json from picker :
__
2018-10-02 10 05 35

You probably didn't setup the storage on firebase, double check it

I have same problems.. It keeps giving error as 'unknown error...' I have tried different ways like uri, path.. but all the time I get these errors..

Error: An unknown error has occurred.
at createErrorFromErrorData (NativeModules.js:146) ...

This is so annoying problem, like what it means even unknown error??

I have the same error when I'm trying to upload any type of file but images

I don't know why, but the unknown error from react-native-firebase storage was that it could not find the image on the phone with the given URI path from Image-Picker response json. Instead of using URI I used the path from Image-Picker response json and insert into .putFile(). Hopefully that works for anyone who's still having this issue. Works only for android, use URI for iOS.

The path should look like this: /storage/emulated/0/DCIM/Camera/IMG_20190621_194603.jpg

Response json from Image Picker:
image

The path should look like this: /storage/emulated/0/DCIM/Camera/IMG_20190621_194603.jpg

I prepended with "file://" to get this to work, on Android only. On my iOS builds, the regular uri was working fine. So I made a little helper to check platform:

getFilePathForPlatform = response => { if (Platform.OS === "ios") { return response.uri; } else { return response.path && "file://" + response.path; } };

hey I have the same issue in android and my file is

file:///data/user/0/com.app/cache/react-native-image-crop-picker/74400586_2755173127911106_8560987225389531136_o.jpg

Having same issue
path is like this
uri: "content://com.android.providers.downloads.documents/document/1015"

The current method that I am using is:

const getFilePath = (platformOS) => async (uri) => {
    if (platformOS === 'ios') {
        return uri
    }
    return (await RNFetchBlob.fs.stat(uri)).path
}

But still does not work, the react-native-firebase version used is: 5.6.0
I double check that my instalation is correct.

The path is like this one before calling the storage method: /storage/emulated/0/Download/Margareth1.jpeg

And the call to the method is:

const decodedUri = await getFilePath(Platform.OS)(uri)
const data = await refStorage.child(uuidv1()).putFile(decodedUri)

Someone manage to fix it?

I am also getting this error in android. My code is

`
const options2 = {
title: 'Select video',
mediaType: 'video',
path: 'video',
quality: 1
};

ImagePicker.showImagePicker(options2, (response) => {
console.log('Response = ', 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 {
firebase.storage().ref().child('vid_my')
.putFile(response.uri, { contentType: 'video/mp4' })
.catch(error => {
console.log('error ' + error)
})
.then((snapshot) => {
console.log(JSON.stringify(snapshot));
})
}
});
`

In my case, I needed to request permissions (android only)

        if (Platform.OS === 'android') {
            await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                {
                    title: permissionRequestTile || 'Access to your files',
                    message: permissionRequestMessage || `
                        To save your file in our servers the application
                        needs to access your files
                    `,
                    buttonNegative: 'Cancel',
                    buttonPositive: 'OK',
                },
            )
        }

The error is not very clear, so we have to guess.

@RANGELJ Thanks. I was using version 5 of react native firebase. I fixed it by migration to version 6.

In case you are using react-native-document-picker, check out this:
https://github.com/rnmods/react-native-document-picker/issues/235

Try changing rules in firebase storage to:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
It worked for me.In IOS and android as well. For "An unknown error occured"

@Piyush-syst do not make recommendations that involve security for other users without carefully examining their use case, security surface area and risks + liabilities. Perhaps they are storing medical records and you just opened them to lawsuits...

Was this page helpful?
0 / 5 - 0 ratings