How to load image and convert to blob in react
22,322
Solution 1
Here's an example how can you use FileReader.readAsDataURL
const {useState} = React;
const fileToDataUri = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result)
};
reader.readAsDataURL(file);
})
const App = () => {
const [dataUri, setDataUri] = useState('')
const onChange = (file) => {
if(!file) {
setDataUri('');
return;
}
fileToDataUri(file)
.then(dataUri => {
setDataUri(dataUri)
})
}
return <div>
<img width="200" height="200" src={dataUri} alt="avatar"/>
<input type="file" onChange={(event) => onChange(event.target.files[0] || null)} />
</div>
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
Solution 2
Use FileReader
fileUploadInputChange(e) {
let reader = new FileReader();
reader.onload = function(e) {
this.setState({uploadedImage: e.target.result});
};
reader.readAsDataURL(event.target.files[0]);
}
To show/preview image:
<Avatar src={this.state.uploadedImage} name="Foo Bar" className={'position-relative button-cursor'}/>
// or .. for image , use below
<img src={this.state.uploadedImage} alt={""} />
Related videos on Youtube
Comments
-
Young L. almost 3 years
Hi I have an issue with react. I have a method which after click is starting to import image. Actualy I have onChangeevent with this method on my file input:
fileUploadInputChange(e) { console.log(e.target.value); // return url of image like C:\fakepath\pokemon-pikachu-wall-decal.jpg };
Now I have to convert this uploaded file to blob. How can I do this please?
My other code looks like this:
export class GeneralySettings extends Component { /** * PropTypes fot component * @return {object} */ static get propTypes() { return { userData: PropTypes.object.isRequired, }; }; constructor(props) { super(props); this.state = { showAvatarChangeButton: false, uploadedImage : '', }; this.inputReference = React.createRef(); } fileUploadAction(){ this.inputReference.current.click(); }; fileUploadInputChange(e){ console.log(e.target.value); }; /** * Render method for user profile * @return {*} */ render() { return ( <div className={'d-flex flex-column mr-2'}> <div className={'position-relative'} onMouseEnter={() => this.setState({showAvatarChangeButton: true})} onMouseLeave={() => this.setState({showAvatarChangeButton: false})}> <Avatar name="Foo Bar" className={'position-relative button-cursor'}/> <div className={`position-absolute ${(this.state.showAvatarChangeButton ? 'd-inlene-block' : 'd-none')}`} id={'changeAvatarButton'}> <Button variant={'dark'} size={'sm'} block onClick={this.fileUploadAction.bind(this)}> Zmeniť</Button> <input type="file" hidden ref={this.inputReference} onChange={(e) => this.fileUploadInputChange(e)}/> </div> </div> ); } }
-
Young L. almost 4 yearsAnd how can i show this image in my img src ?? Becouse reader.readDataAsUrl not returning anything