Programing

이미지 경로를 BLOB reactive native로 변환

c10106 2022. 3. 12. 10:00
반응형

이미지 경로를 BLOB reactive native로 변환

문제

나는 리액션 네이티브와 파이어베이스로 앱을 만들려고 한다.이 앱에서 내가 원하는 기능 중 하나는 이미지 업로드 기능이다.화기 저장소에 이미지를 업로드하는 데 문제가 좀 있어.엑스포 이미지 선택기를 이용해 사용자가 업로드하고자 하는 이미지의 경로를 찾고 있지만 일단 그 경로를 갖게 되면 그것을 소방본부로 올릴 수 있는 것으로 변환할 수 있는 방법을 알 수 없다.

누군가가 내가 이미지의 경로를 리액션 네이티브를 사용하여 소방 기지 스토리지에 업로드할 수 있는 것으로 변환할 수 있도록 도와줄 수 있는가?

내가 노력한 것

다음을 사용해 보십시오.

     _pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      MediaTypeOptions: 'Images',
      quality: 0.4,
_uploadAsByteArray = async (pickerResultAsByteArray, progressCallback) => {

    try {

      var metadata = {
        contentType: 'image/jpeg',
      };

      var storageRef = firebase.storage().ref();
      var ref = storageRef.child('images/'+expoID+'/'+this.state.time)
      let uploadTask = ref.put(pickerResultAsByteArray, metadata)

      uploadTask.on('state_changed', function (snapshot) {

        progressCallback && progressCallback(snapshot.bytesTransferred / snapshot.totalBytes)

        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');

      }, function (error) {
        console.log("in _uploadAsByteArray ", error)
      }, function () {
        var downloadURL = uploadTask.snapshot.downloadURL;
        console.log("_uploadAsByteArray ", uploadTask.snapshot.downloadURL)
    this.setState({imageUploaded:true})
      });


    } catch (ee) {
      console.log("when trying to load _uploadAsByteArray ", ee)
    }
  }


  convertToByteArray = (input) => {
    var binary_string = this.atob(input);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes
  }

  atob = (input) => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

    let str = input.replace(/=+$/, '');
    let output = '';

    if (str.length % 4 == 1) {
      throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
    }
    for (let bc = 0, bs = 0, buffer, i = 0;
      buffer = str.charAt(i++);

      ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
        bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
    ) {
      buffer = chars.indexOf(buffer);
    }

    return output;
  }


uploadImage(bsfdata){
    this.setState({imageUploaded:false})
    this._uploadAsByteArray(this.convertToByteArray(bsfdata), (progress) => {
    this.setState({ progress:progress })
    })
  }
  base64:true,
});



 /* if (!result.cancelled) {
      this.setState({ image: result.uri });
      let formData = new FormData();
        formData.append('photo', {
           uri,
           name: `photo.${fileType}`,
           type: `image/${fileType}`,
     });}*/
      this.uploadImage(result.base64);
  };

}

아무 것도 업로드되지 않는 코멘트가 추가된 코드로 시도해 봤고, 지금 코드가 어떻게 되어 있는지 시도해 봤더니 오류가 난다.Can currently only create a Blob from other Blobs업로딩 진행률은 0%를 넘지 않는다.

엑스포(>>=26)를 사용하고 있다면, 다음과 같은 코드 라인으로 쉽게 할 수 있다.

uploadImage = async(imageUri) => {
  const response = await fetch(imageUri);
  const blob = await response.blob();
  var ref =   firebase.storage().ref().child("image.jpg");
  return ref.put(blob);
}

참조: https://youtu.be/KkZckepfm2Q

이 링크를 참조하십시오. https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69

다음 코드 블록은 잘 작동하고 있다.

uploadImage(uri, mime = 'application/octet-stream') {
    return new Promise((resolve, reject) => {
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
      let uploadBlob = null

      const imageRef = FirebaseClient.storage().ref('images').child('image_001')

      fs.readFile(uploadUri, '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) => {
          resolve(url)
        })
        .catch((error) => {
          reject(error)
      })
    })
  }

설치해야 함rn-fetch-blob모듈:

npm install --save rn-fetch-blob

그런 다음 다음을 수행하십시오.

import RNFetchBlob from 'rn-fetch-blob';

const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;

function uploadImage(path) {
    const imageFile = RNFetchBlob.wrap(path);

    // 'path/to/image' is where you wish to put your image in
    // the database, if you would like to put it in the folder
    // 'subfolder' inside 'mainFolder' and name it 'myImage', just 
    // replace it with 'mainFolder/subfolder/myImage'
    const ref = firebase.storage().ref('path/to/image');
    var uploadBlob = null;

    Blob.build(imageFile, { type: 'image/jpg;' })
        .then((imageBlob) => {
            uploadBlob = imageBlob;
            return ref.put(imageBlob, { contentType: 'image/jpg' });
        })
        .then(() => {
            uploadBlob.close();
            return ref.getDownloadURL();
        })
        .((url) => {
            // do something with the url if you wish to
        })
        .catch(() => {
            dispatch({
                type: UPDATE_PROFILE_INFO_FAIL,
                payload: 'Unable to upload profile picture, please try again'
            });
        });
}

네가 모르는 코드 부분이 있는지 물어봐 줘.여러 이미지를 업로드하려면 이 코드를 for 루프(for loop)로 감싸기만 하면 된다.또는 모든 이미지가 오류 없이 업로드되도록 하려면Promise

이 방법이 누구에게 도움이 될지는 모르겠지만, 만약 당신이MediaLibrary화랑에서 이미지를 로드하면 uri는uri = file:///storage/emulated/0/DCIM/Camera/filename.jpg

이 경우 사용fetch(uri)내가 해고당하는 걸 도와주지 않았어

하지만 만약 당신이 사용한다면fetch(uri.replace("file:///","file:/"))그리고 @sriteja Sugoor의 대답을 따르면, 파일 blob을 업로드할 수 있을 것이다.

const Blob = RNFetchBlob.polyfill.Blob;
      const fs = RNFetchBlob.fs;
      let uploadBlob;
      await fs
        .readFile(params?.file.path, 'base64')
        .then((data) => {
          return Blob.build(data, {type: `BASE64`});
        })
        .then((blob) => {
          uploadBlob = blob;
          console.log(uploadBlob, 'uploadBlob');
        });

참조URL: https://stackoverflow.com/questions/48108791/convert-image-path-to-blob-react-native

반응형