在React Native中显示Blob图像(Expo)

时间:2019-04-29 15:12:16

标签: react-native blob microsoft-graph expo

我在我的react native项目中具有以下访存函数以从MS Graph返回blob图像,该返回有效,但我似乎无法将blob显示为图像。

        //Blob Picture
      fetch('https://graph.microsoft.com/v1.0/me/photo/$value', {
        headers: { 'Authorization': "Bearer " + accessToken },
      })
        .then((response) => {
          // console.log(response);
               this.setState({ BlobImage: response});
        })
        .catch((error) => {
          console.error(error);
        });

然后,我希望这样显示图像:

   <Image source={{uri: BlobImage}} style={{ height: 200, width: null, flex: 1 }}/>

3 个答案:

答案 0 :(得分:0)

一种方法是将blob转换为base64并将其用作uri,如here中所述 但是我更愿意使用rn-fetch-blob并使用path,因为它更直接。检查此示例:

RNFetchBlob
  .config({
    fileCache : true,
    // by adding this option, the temp files will have a file extension
    appendExt : 'png'
  })
  .fetch('GET', 'http://www.example.com/file/example.zip', {
    //some headers ..
  })
  .then((res) => {
    // the temp file path with file extension `png`
    console.log('The file saved to ', res.path())
    // Beware that when using a file path as Image source on Android,
    // you must prepend "file://"" before the file path
    imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path() }}/>
  })

答案 1 :(得分:0)

尽管已经有一个答案,并且被标记为已解决,但我在此处添加了解决方案。

我尝试了react-native-fetch-blob,但没有成功。

最初,我将responseType设置为'arraybuffer'

const photo = await graph.get('/me/photo/$value', {
      responseType: 'arraybuffer'
    });

现在响应在photo.data中具有一个数组缓冲区

const state = {
            photo: photo.data
};

在我的屏幕上,我已经使用包base64-arraybuffer显示了图像。

import Base64ArrayBuffer from 'base64-arraybuffer';
...
const photoURI = Base64ArrayBuffer.encode(state.photo);
...
<Image style={styles.profilePhoto} source={{ uri: `data:image/jpg;base64,${photoURI}` }} />

答案 2 :(得分:0)

经过大量时间浪费后,这在React Native> 0.60和Expo上使用react-native-image-picker或expo-image-picker和axios效果很好。

const {uri} = file;
const uriParts = uri.split('.');
const fileType = 'image/' + uriParts[uriParts.length - 1];

const data = new FormData();
data.append('image', {type: fileType, uri: uri, name: 'image'});
data.append('first_name', 'John Doe')

const req = await axios.post(url, data, {headers: {'Content-Type': 'multipart/form-data'} });