Last active
October 27, 2023 18:09
-
-
Save pirey/9b0a0a86d2593dbbf5fccbb04fb4b2ac to your computer and use it in GitHub Desktop.
react file input, convert File to source url, useful to preview image before uploading
This file contains hidden or 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
| import {readFileAsUrl} from './readFileAsUrl' | |
| class Example extends React.Component { | |
| constructor() { | |
| this.state = { | |
| previewUrl: '' | |
| } | |
| } | |
| render() { | |
| return ( | |
| <div> | |
| <img src={this.state.previewUrl} /> | |
| <input onChange={this.onChange.bind(this)} | |
| </div> | |
| ) | |
| } | |
| onChange (event) { | |
| const file = event.target.files[0] | |
| readFileAsUrl(file).then(url => { | |
| this.setState({ | |
| previewUrl: url | |
| }) | |
| event.target.value=null // reset file value, so can select the same file again | |
| }) | |
| } | |
| } |
This file contains hidden or 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
| export function readFileAsUrl (file) { | |
| return new Promise((resolve, reject) => { | |
| const reader = new window.FileReader() | |
| reader.onload = e => { | |
| const src = e.target.result | |
| resolve(src) | |
| } | |
| reader.readAsDataURL(file) | |
| }) | |
| } |
This file contains hidden or 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
| // typescript version | |
| export function readFileAsUrl (file: File): Promise<string> { | |
| return new Promise((resolve, reject) => { | |
| const reader = new FileReader() | |
| reader.onload = (event: any) => { | |
| const src = event.target.result | |
| resolve(src) | |
| } | |
| reader.readAsDataURL(file) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment