Rockettomatoo
Rockettomatoo

Reputation: 277

Meteor React: Render Image from Array Buffer

I try to write a component which renders a picture fetched from a REST-Server. I have to fetch the picture on the server-side because I don't want to expose the REST-Server to the Internet. Because of this, i can't simply put an "img" tag in the html. (The REST-Server runs on the same system as the Meteor-Server).

Lets say, the Meteor-Method "get_picure" fetches the picture from the REST-Server and returns it to the component. The returned object is the plain result from a synchronous HTTP.call-request.

Picture.jsx

import React, { Component, PropTypes } from 'react';

export default class Picture extends Component {
  propTypes: {
    picture: PropTypes.string.isReqired,
    style: Proptypes.object,
  }

  constructor(props) {
    super(props);

    this.state = {
      pic: null,
      style: this.props.style
    }

    //invoke the server to fetch the picture
    Meteor.call("get_picture", this.props.picture, this.update.bind(this));
  }

  //callback for Meteor.call
  update(error,data) {
    if(error || data.statusCode != 200) {
      return;
    }

    //data.content is an "uint8Array" due to the { npmRequestOptions: {encoding: null}} option set in the HTTP-Request
    this.setState({pic: data.content});
  }

  render() {
    return (
      <span style={this.state.style}>
        { this.state.pic ? this.state.pic : "" }
      </span>
    )
  }
}

All I get, are numbers displayed in the given "span"-tag.

Is there a way, to display the picture from a state-variable?

Upvotes: 1

Views: 5168

Answers (1)

Rockettomatoo
Rockettomatoo

Reputation: 277

After a bit of googling, I found an answer. A working solution is to encode the existing uint8array to base64.

export default class Picture extends Component {
...
    update(error,data) {
        ...
        //encode to base64
        var image = btoa(String.fromCharCode.apply(null, data.content);

        this.setState({pic: "data:image/png;base64," + image});
    }
...
}

To display this, I set the src-Attribute from an <img />-Tag to this.state.pic. This causes the fetched image to display in the generated <img />-Tag.

Note: "data:image/png" represents the content-type from the fetched image and can be replaced with any other image-content-type (for example image/jpeg).

Upvotes: 1

Related Questions