Is it possible to get the binary data from an image in React-Native?

前端 未结 2 803
独厮守ぢ
独厮守ぢ 2021-02-15 16:58

I\'m using react-native-camera and I\'m having trouble getting the image as binary data in react-native. I need this to be able to upload images to our

相关标签:
2条回答
  • 2021-02-15 17:43

    If you want to get image as binary data from react-native-camera. I recommend to use react-native-fs to read uri

    Example

    const RNFS = require("react-native-fs");
    // response.uri from react-native-camera
    RNFS.readFile(response.uri, "base64").then(data => {
      // binary data
      console.log(data);
    });
    

    If you want to upload image via FormData I recommend rn-fetch-blob

    Example

    import RNFetchBlob from 'rn-fetch-blob'
    // response.uri from react-native-camera
    const path = response.uri.replace("file://", "");
    const formData = [];
    formData.push({
      name: "photo",
      filename: `photo.jpg`,
      data: RNFetchBlob.wrap(path)
    });
    
    let response = await RNFetchBlob.fetch(
      "POST",
      "https://localhost/upload",
      {
        Accept: "application/json",
        "Content-Type": "multipart/form-data"
      },
      formData
    );
    
    0 讨论(0)
  • 2021-02-15 17:50

    An alternative if you're already using react-native-camera is upon capturing the image, you request it as base64 directly as such:

    takePicture = async function(camera) {
      const options = { quality: 0.5, base64: true, doNotSave: true }
      const data = await camera.takePictureAsync(options)
    
      console.log(data.base64)
    }
    

    If your goal is to only snap the picture, show a preview perhaps then upload to the server and move on, then the benefit of this approach is that it won't save that photo in your device cache (doNotSave: true). Which means that you don't need to worry about cleaning those up after you're done.

    0 讨论(0)
提交回复
热议问题