Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JimiSweden/d39ecfd79c0fe1887140f920b1ba6008 to your computer and use it in GitHub Desktop.
Save JimiSweden/d39ecfd79c0fe1887140f920b1ba6008 to your computer and use it in GitHub Desktop.
javscript / react read image from database buffer array convert to base64 using Window.btoa()
// full example : https://medium.com/@colinrlly/send-store-and-show-images-with-react-express-and-mongodb-592bc38a9ed
// index.js
import React, { Component } from 'react';
class Image extends Component {
constructor(props) {
super(props);
this.state = {
img: ''
};
};
// from https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string
// alternative (non native approach) - https://gist.github.com/jonleighton/958841
arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};
componentDidMount() {
fetch('http://yourserver.com/api/img_data')
.then((res) => res.json())
.then((data) => {
var base64Flag = 'data:image/jpeg;base64,';
var imageStr =
this.arrayBufferToBase64(data.img.data.data);
this.setState({
img: base64Flag + imageStr
)}
})
}
render() {
const {img} = this.state;
return (
<img
src={img}
alt='Helpful alt text'/>
)
}
export default Image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment