Academind Logo

Image Upload

Too many people are struggling with image upload in React.js apps. This article and video changes it.

Created by Maximilian Schwarzmüller

React.js Image Upload

Uploading images basically is a two-step process:

  1. Select a file


Select a File

Before we can upload it, we have to select a file.

To allow the user to pick a file, we have to add <input type="file"> to our component JSX code. We also have to listen to any changes to that file. Such a change handler will trigger whenever the user picks a new file.

Like this:

<input type="file" onChange={this.fileChangedHandler}>
<button onClick={this.uploadHandler}>Upload!</button>

We now need the two handler methods in our React component:

fileChangedHandler = (event) => {
const file =[0]
uploadHandler = () => { ... }

To upload the file, we should store it in our state:

state = { selectedFile: null }
fileChangedHandler = event => {
this.setState({ selectedFile:[0] })
uploadHandler = () => {

Send the File to a Server

With the file stored in state, we can send it to a server.

For this, you can use axios. You can either send the file as binary data or wrapped in a FormData object - depending on what your REST API expects.

Send as binary data

uploadHandler = () => {'', this.state.selectedFile)

Send as FormData

uploadHandler = () => {
const formData = new FormData()
)'', formData)

Show upload progress

In both cases, you can also output the upload progress if you want to.

uploadHandler = () => {
...'', formData, {
onUploadProgress: progressEvent => {
console.log(progressEvent.loaded /

Recommended Courses