Created
April 3, 2020 12:04
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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