Giter VIP home page Giter VIP logo

react-native-get-real-path's Introduction

react-native-get-real-path

Get real file path from file uri

Installation (iOS)

Currently No Support

Installation (Android)

npm i react-native-get-real-path@https://github.com/Wraptime/react-native-get-real-path.git --save

Make alterations to the following files:

  • android/settings.gradle
...
include ':react-native-get-real-path'
project(':react-native-get-real-path').projectDir = new File(settingsDir, '../node_modules/react-native-get-real-path/android')
  • android/app/build.gradle
...
dependencies {
    ...
    implementation project(':react-native-get-real-path')
}
  • register module (in MainActivity.java)

    • For react-native below 0.19.0 (use cat ./node_modules/react-native/package.json | grep version)
import com.rngrp.RNGRPPackage;  // <--- import

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

  ......

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplication())
      .setBundleAssetName("index.android.bundle")
      .setJSMainModuleName("index.android")
      .addPackage(new MainReactPackage())
      .addPackage(new RNGRPPackage())      // <------- add package
      .setUseDeveloperSupport(BuildConfig.DEBUG)
      .setInitialLifecycleState(LifecycleState.RESUMED)
      .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "ExampleRN", null);

    setContentView(mReactRootView);
  }

  ......

}
  • For react-native 0.19.0 and higher
import com.rngrp.RNGRPPackage; // <------- add package

public class MainActivity extends ReactActivity {
   // ...
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(), // <---- add comma
        new RNGRPPackage() // <---------- add package
      );
    }

Example usage (Android only)

// require the module
var RNGRP = require('react-native-get-real-path');

RNGRP.getRealPathFromURI(fileUri).then(filePath =>
  console.log(filePath)
)

Use Case - get images from CameraRoll as base64

RNGRP.getRealPathFromURI(imageUri).then(path =>
  RNFS.readFile(path, 'base64').then(imageBase64 =>
    console.log(imageBase64)
  )
)

react-native-get-real-path's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-get-real-path's Issues

RNGRP returns null

// im selecting a video using react-native-image-picker

ImagePicker.showImagePicker(options, response => {

            RNGRP.getRealPathFromURI(response.uri).then(path=>{
              console.log(path);  //returns null
            })
});

error: bundling failed: Error: Unable to resolve module `react-native-get-real-path` from `App.js`: react-native-get-real-path could not be found within the project.

error: bundling failed: Error: Unable to resolve module `react-native-get-real-path` from `App.js`: react-native-get-real-path could not be found within the project.

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules: rm -rf node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
    at ModuleResolver.resolveDependency (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:186:15)
    at ResolutionRequest.resolveDependency (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
    at DependencyGraph.resolveDependency (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/node-haste/DependencyGraph.js:282:16)
    at Object.resolve (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/lib/transformHelpers.js:267:42)
    at dependencies.map.result (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:426:31)
    at Array.map (<anonymous>)
    at resolveDependencies (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:423:18)
    at /home/buddhi/react-tutorials/firstapp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:275:33
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/home/buddhi/react-tutorials/firstapp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)

I'm using Ubuntu 19.10. Moreover, I have installed the package properly. here is the App.js code;

import RNGRP from 'react-native-get-real-path';

async MultipleFilePicker() {
    try {
      const res = await DocumentPicker.pickMultiple({
        type: [DocumentPicker.types.allFiles],

      });

      for (const results of res) {
        //Printing the log realted to the file
        console.log('res : ' + JSON.stringify(results));
        console.log('URI : ' + results.uri);
        console.log('Type : ' + results.type);
        console.log('File Name : ' + results.name);
        console.log('File Size : ' + results.size);

        //get the files URI
        let url = results.uri;
        const split = url.split('/');
        const name = split.pop();
        const inbox = split.pop();

        // Create an accesible file path
        const realPath = `${RNFS.TemporaryDirectoryPath}${inbox}/${name}`;
        // Print the file path
        console.log('real path' + realPath);

        RNGRP.getRealPathFromURI(realPath).then(filePath =>
          console.log("RNGRP : "+ filePath)
        )

        // Recheck if the selected file exists
        RNFS.exists(realPath).then((success) => {
          console.log('FILE exists!');
          console.log('Success result' + success);
        }).catch((err) => {
          console.log('Returned an error!');
          console.log(err.message);
        })
      }

      this.setState({ multipleFile: res });


    } catch (err) {
      if (DocumentPicker.isCancel(err)) {
        Alert.alert('Canceled');
      } else {
        Alert.alert('Unknown Error: ' + JSON.stringify(err));
        throw err;
      }
    }
  }

Crashes iOS app

It crashes trying to run the app on iOS.

Can you check if GRP is defined in GRP.common.js line 14 to avoid this issue?

Replace line:
var _getRealPathFromURI = Promise.promisify(GRP.getRealPathFromURI);

with:
var _getRealPathFromURI = Promise.promisify(GRP ? GRP.getRealPathFromURI : (fileUri)=>{ return fileUri; });

Thanks!

Error: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object

When excuting the code below,

RNGRP.getRealPathFromURI(payload.uri)
    .then((filePath: string) => console.log(filePath))
    .catch((error: string) => console.log(error));

It raises an error saying:

Error: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
    at convertError (GRP.common.js:21)
    at tryCatcher (bluebird.js:4594)
    at Promise._settlePromiseFromHandler (bluebird.js:2698)
    at Promise._settlePromiseAt (bluebird.js:2772)
    at Promise._settlePromises (bluebird.js:2888)
    at Async._drainQueue (bluebird.js:175)
    at Async._drainQueues (bluebird.js:185)
    at Async.drainQueues (bluebird.js:67)
    at JSTimers.js:301
    at _callTimer (JSTimers.js:154)
    at _callImmediatesPass (JSTimers.js:202)
    at Object.callImmediates (JSTimers.js:470)
    at MessageQueue.__callImmediates (MessageQueue.js:329)
    at MessageQueue.js:147
    at MessageQueue.__guardSafe (MessageQueue.js:316)
    at MessageQueue.flushedQueue (MessageQueue.js:146)

(I tried this solution to build successfully: #10 (comment))

Error with Telegram

content://org.telegram.messenger.provider/media/Telegram/Telegram%20Documents/2_5314352464873390192.mab

Unhandled rejection convertError@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:102543:24
tryCatcher@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:106868:40
_settlePromiseFromHandler@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:105107:51
_settlePromiseAt@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:105179:59
_settlePromises@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:105284:46
_drainQueue@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:102752:43
_drainQueues@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:102762:33
drainQueues@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:102641:38
http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:3440:24
callTimer@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2207:17
callImmediatesPass@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2293:36
callImmediates@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2303:48
http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2074:48
__guard@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2062:11
__callImmediates@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2073:19
http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:1974:32
__guard@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:2062:11
invokeCallbackAndReturnFlushedQueue@http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:1972:19
invokeCallbackAndReturnFlushedQueue@[native code]'

jcenter server has been sunset; updating to mavenCentral.

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Found that center has been sunset and it's recommended to use mavenCentral or Google to fetch dependencies.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-get-real-path/android/build.gradle b/node_modules/react-native-get-real-path/android/build.gradle
index 2da2b35..086bf0a 100644
--- a/node_modules/react-native-get-real-path/android/build.gradle
+++ b/node_modules/react-native-get-real-path/android/build.gradle
@@ -1,10 +1,15 @@
 buildscript {
     repositories {
-        jcenter()
+        mavenCentral()
+        mavenLocal()
+        google()
+        maven {
+            url 'https://maven.google.com'
+        }
     }
 
     dependencies {
-        classpath 'com.android.tools.build:gradle:2.2.+'
+        classpath 'com.android.tools.build:gradle:4.1.3'
     }
 }
 

This issue body was partially generated by patch-package.

Permission denial READ_EXTERNAL_STORAGE

when getContentResolver is called, through exception : Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=18708, uid=10127 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission().
Although I try to add :
"uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" "
to manifest but exception still the same.

Not working in the react-native Version 0.71+

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':react-native-get-real-path'.

Could not determine the dependencies of null.
Cannot invoke method get() on null object

  • Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or
plugins.

See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 29s
5 actionable tasks: 5 up-to-date
this is the error log when tried to run the app or executing the cmd gradlew assembleDebug.
can anyone help me with this issue ?

Android 8,9,10 - issue on emulator with getRealPathFromURI - NumberFormatException

Hi, I have issue with get image from downloads file on emulator.
My path: content://com.android.providers.downloads.documents/document/msf%3A253

And I've got this error:
java.lang.NumberFormatException: For input string: "msf:253"/ System.err: at java.lang.Long.parseLong(Long.java:594) W/System.err: at java.lang.Long.valueOf(Long.java:808) W/System.err: at com.rngrp.GRP.getRealPathFromURI(GRP.java:75)

Is it connected to testing on emulator?

I am using:

Android:
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
RN:
"react": "16.9.0",
"react-native": "0.61.4",

Error while building react native app: Could not resolve all artefacts for configuration react-native-get-real-path

Environment

React native version: 0.62.2,
react-native-get-real-path: "git+https://github.com/Wraptime/react-native-get-real-path.git",
Gradle version 3.3.0,
Dependency in react-native-get-real-path's build.gradle file: Gradle version 2.2.+

Description

I try to run the app with react-native run-android or if I run ./gradlew clean in the android folder, I get the error:

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':react-native-get-real-path'.

Could not resolve all artifacts for configuration ':react-native-get-real-path:classpath'.
Could not resolve com.android.tools.build:gradle:2.2.+.
Required by:
project :react-native-get-real-path
> Failed to list versions for com.android.tools.build:gradle.
> Unable to load Maven meta-data from https://jcenter.bintray.com/com/android/tools/build/gradle/maven-metadata.xml.
> Could not HEAD 'https://jcenter.bintray.com/com/android/tools/build/gradle/maven-metadata.xml'.
> org.apache.http.client.ClientProtocolException (no error message)

I didn't change anything in the project and it was working fine a while ago.
I've deleted and reinstalled node modules, cleared caches, ran it on another android environment, but I keep getting this error.
I also added google() as the repositories in react-native-get-real-path's build.gradle file, all to no avail.

Reproducible Demo

Building the project with the mentioned RN, Gradle and react-native-get-real-path versions.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.