React Native Image with 'Bearer' authentication token

For me the answer from blink281 didn't work. It seems this is a common Android problem according to this thread https://github.com/facebook/react-native/issues/25945 and while writing this it's not fixxed. I was looking for another solution and the answer from Samuli Hakoniemi helped me build one, so i wanted to share a fully working example as his Link is not working anymore.

I created an external Component called NetworkImage for this.

import React from "react";
import { StyleSheet, View, Image } from "react-native";

class NetworkImage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      base64: null,
    };
    this.style = props.style;
    this.imageId = props.imageId;
    this.token = props.token;
  }
  componentDidMount() {
    var imageUri = "/auth/diary/image/" + this.imageId;
    fetch(imageUri, {
      method: "GET",
      headers: {
        Pragma: "no-cache",
        "x-access-token": this.token,
      },
      redirect: "follow",
    })
    .then((res) => res.text())
    .then((content) => {
      let data =
        "data:image/jpeg;base64," +
        content.substring(1, content.length - 1);
      this.setState({
        base64: data,
      });
    });
    });
  }
  render() {
    return <Image style={this.style} source={{ uri: this.state.base64 }} />;
  }
}

export default NetworkImage;

In this case i had to prepend "data:image/jpeg;base64," because the data i got is raw without the datatype.


    import RNFetchBlob from "rn-fetch-blob";

    const { config, fs } = RNFetchBlob;
    let PictureDir = fs.dirs.PictureDir;
    let date = new Date();
    let options = {
      fileCache: true,
      addAndroidDownloads: {
        //Related to the Android only
        useDownloadManager: true,
        notification: true,
        path:
          PictureDir +
          "/Report_Download" +
          Math.floor(date.getTime() + date.getSeconds() / 2),
        description: "Risk Report Download",
      },
    };
    config(options)
    .fetch('GET', url, {
      Authorization: token,
      
    })
      // when response status code is 200
      .then((res) => {
        // the conversion is done in native code
        console.log(JSON.stringify(res));
        alert('report download successfully')

      })
      // Status code is not 200
      .catch((errorMessage, statusCode) => {
        // error handling
        console.log('errorMessage', errorMessage);
        console.log('statusCode', statusCode);

      })

that's all. enjoy your coding...


You can send headers in the source prop.

<Image
    source={
    { uri: 'https://yourdomain.com/get-image',
      headers: {
                Authorization: 'Bearer xyz'
               }
            }
     }/>

you can specify other parameters as well: ImageSourcePropType.js

Tags:

React Native