javascript – cannot create directory in android storage in react native cli

hello there I am new to mobile development and I am trying to make an app but I am stuck due to RNFetchBlob not working properly. the problem is RNFetchBlob doesnt make directory in android storage. even if i create directory, it isnt detected by isDir. Any kind of help woulld be appreciated. Thanks

below is my code :

import React, {useRef, useState, useEffect} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Image,
  Platform,
  PermissionsAndroid,
} from 'react-native';
import Permissions from 'react-native-permissions';
import PDFScanner from '@woonivers/react-native-document-scanner';
import ImageCropPicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'rn-fetch-blob'; //making dir & showimge the image
// import ReactNativeBlobUtil from 'react-native-blob-util';

export default function Scanner() {
  const pdfScannerElement = useRef(null);
  const [data, setData] = useState({});
  const [allowed, setAllowed] = useState(false);
  const [storagePermission, setStoragePermission] = useState(false);

  function checkAndGrantStoragePermission() {
    PermissionsAndroid.check(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    ).then(isPermitted => {
      if (isPermitted) {
        setStoragePermission(true);
      } else {
        PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          (rationale = {
            message: 'Please Give Access to Save Image',
            title: 'Storage Permission',
          }),
        ).then((data: string) => {
          setStoragePermission(true);
        });
      }
    });
  }

  // async function checkAndroidPermission() {
  //   try {
  //     const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
  //     await PermissionsAndroid.request(permission);
  //     Promise.resolve();
  //   } catch (error) {
  //     console.log('checkAndroidPermission: ' + error);
  //     Promise.reject(error);
  //   }
  // }

  useEffect(() => {
    async function requestCamera() {
      const result = await Permissions.request(
        Platform.OS === 'android'
          ? 'android.permission.CAMERA'
          : 'ios.permission.CAMERA',
      );
      if (result === 'granted') setAllowed(true);
    }
    requestCamera();
  }, []);

  function handleOnPressRetry() {
    setData({});
  }
  function saveInGallery() {
    checkAndGrantStoragePermission();
    // checkAndroidPermission();
    // ImageCropPicker.openPicker(options{includeBase64:true}).then(image => {  });
    // console.log(data);
    const raw = JSON.stringify(data); //converting data coming from scanner to string
    const fileName = raw.split(','); //splitting the raw to get the initial & cropped image info
    const initial = fileName[0].split("https://stackoverflow.com/"); //splitting the initial image info to get the name
    const cropped = fileName[1].split("https://stackoverflow.com/"); //splitting the cropped image info to get the name
    const initialFileName = initial[initial.length - 1]; //getting the initial image name from splitted array
    const croppedFileName = cropped[cropped.length - 1]; //getting the cropped image name from splitted array
    const filePathInitial = fileName[0].split('":"'); //splitting the fileName info to get the initial path
    const filePathCrop = fileName[1].split('":"'); //splitting the fileName info to get the cropped path
    console.log('rawFileName: ' + fileName);
    console.log('ini: ' + initial);
    console.log('cropped: ' + cropped);
    console.log('initialFileName: ' + initialFileName);
    console.log('croppedFileName: ' + croppedFileName);
    console.log('iniFilepath: ' + filePathInitial);
    console.log('cropFilepath: ' + filePathCrop);

    const inifinalPath = filePathInitial[1].split('///');
    console.log('inifinalPath: ' + inifinalPath[1]);
    const cropfinalPath = filePathCrop[1].split('///');
    console.log('cropfinalPath: ' + cropfinalPath[1]);
    saveImage("https://stackoverflow.com/" + inifinalPath[1], initialFileName);
    saveImage("https://stackoverflow.com/" + cropfinalPath[1], initialFileName);
  }

  function saveImage(source: string, fileName: string) {
    const folderPath="/storage/emulated/0/camScanner";
    const filePath = folderPath + "https://stackoverflow.com/" + fileName;
    RNFetchBlob.fs.isDir(folderPath).then((isDir: boolean) => {
      if (isDir) {
        console.log('folder exists');
        addImage(source, filePath);
      } else {
        console.log('folder does not exist');
        RNFetchBlob.fs
          .mkdir(folderPath)
          .then(() => {
            addImage(source, filePath);
          })
          .catch(err => {
            console.log(err);
          });
      }
    });
  }
  function addImage(source: string, path: string) {
    RNFetchBlob.fs.createFile(path, source, (encoding = 'base64')).then(() => {
      console.log('file created');
    });
  }

  function handleOnPress() {
    pdfScannerElement.current.capture();
  }
  if (!allowed) {
    console.log('You must accept camera permission');
    return (
      <View style={styles.permissions}>
        <Text>You must accept camera permission</Text>
      </View>
    );
  }
  if (data.croppedImage) {
    console.log('data', data);
    return (
      <React.Fragment>
        <Image source={{uri: data.croppedImage}} style={styles.preview} />
        <View style={{flexDirection: 'row'}}>
          <View>
            <TouchableOpacity
              onPress={handleOnPressRetry}
              style={styles.button}>
              <Text style={styles.buttonText}>Retry</Text>
            </TouchableOpacity>
          </View>
          <View>
            <TouchableOpacity onPress={saveInGallery} style={styles.button}>
              <Text style={styles.buttonText}>Save</Text>
            </TouchableOpacity>
          </View>
        </View>
      </React.Fragment>
    );
  }
  return (
    <React.Fragment>
      <PDFScanner
        ref={pdfScannerElement}
        style={styles.scanner}
        onPictureTaken={setData}
        overlayColor="rgba(255,130,0, 0.7)"
        enableTorch={false}
        quality={0.5}
        detectionCountBeforeCapture={5}
        detectionRefreshRateInMS={50}
        noGrayScale={true}
      />
      <TouchableOpacity onPress={handleOnPress} style={styles.button}>
        <Text style={styles.buttonText}>Take picture</Text>
      </TouchableOpacity>
    </React.Fragment>
  );
}

Leave a Comment