将图像路径转换为blob反应原生

时间:2018-01-05 07:07:10

标签: javascript firebase react-native firebase-storage

问题

我正在尝试使用react native和firebase创建一个应用程序。我想要这个应用程序的功能之一是上传图像的能力。我在将图像上传到firebase存储时遇到了一些麻烦。我正在使用世博会的图像选择器来查找用户想要上传的图像的路径,但是一旦我有了这条路径,我就不知道如何将其转换为我可以上传到firebase的内容。 / p>

有人可以帮助我将图片的路径转换为我可以使用react native上传到firebase存储的内容吗?

我尝试了什么

我尝试使用:

     _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%。

5 个答案:

答案 0 :(得分:2)

如果您正在使用expo(> = 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

答案 1 :(得分:0)

react-native-fs用于readFile到数据/二进制文件(转换为base64格式字符串)。

然后你可以将数据上传到firebase。

示例:

RNFS.readFile(uri, 'utf8')
    .then( (result) => console.log(result) );

注意:对于Android从资源中读取文件,请改用readFileAssets

答案 2 :(得分:0)

您需要安装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循环包装此代码即可。或者,如果您想确保上传的每张图片都没有任何错误,请使用Promise

答案 3 :(得分:0)

请参考此链接-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)
      })
    })
  }

答案 4 :(得分:0)

不确定这可能对谁有帮助,但是如果您使用MediaLibrary从图库中加载图像,则uri的格式为uri = file:///storage/emulated/0/DCIM/Camera/filename.jpg

在这种情况下,使用fetch(uri)并不能帮助我解决问题。

但是,如果您使用fetch(uri.replace("file:///","file:/")),然后按照@sriteja Sugoor的回答进行操作,则可以上传文件blob。