I'm new to react js. I want to upload image asynchronously with react js Suppose I have this code
var FormBox = React.createClass({
getInitialState: function () {
return {
photo: []
}
},
pressButton: function () {
var data = new FormData();
data.append("photo", this.state.photo);
// is this the correct way to get file data?
},
getPhoto: function (e) {
this.setState({
photo: e.target.files[0]
})
},
render: function () {
return (
<form action='.' enctype="multipart/form-data">
<input type='file' onChange={this.getPhoto}/>
<button onClick={this.pressButton}> Get it </button>
</form>
)
}
})
ReactDOM.render(<FormBox />, document.getElementById('root'))
Any answer will be appreciated!
You can use whatwg-fetch to make a post request. In your
pressButton()
function make the following changes -You can make use of
FileReader
Use following module to select images.
https://www.npmjs.com/package/react-image-uploader
You can then upload image to server using xhr request. Following is the sample code.
You can use React Dropzone Uploader, which gives you a dropzone that shows file previews (including image thumbnails) for dropped or chosen files, and also handles uploads for you.
Uploads have progress indicators, and they can be cancelled or restarted. The UI is totally customizable, and the library has no dependencies.
Full disclosure: I wrote this library.