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 = event.target.files[0]
}
uploadHandler = () => { ... }

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

state = { selectedFile: null }
fileChangedHandler = event => {
this.setState({ selectedFile: event.target.files[0] })
}
uploadHandler = () => {
console.log(this.state.selectedFile)
}
#

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 = () => {
axios.post('my-domain.com/file-upload', this.state.selectedFile)
}

Send as FormData

uploadHandler = () => {
const formData = new FormData()
formData.append(
'myFile',
this.state.selectedFile,
this.state.selectedFile.name
)
axios.post('my-domain.com/file-upload', formData)
}

Show upload progress

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

uploadHandler = () => {
...
axios.post('my-domain.com/file-upload', formData, {
onUploadProgress: progressEvent => {
console.log(progressEvent.loaded / progressEvent.total)
}
})
}

Recommended Courses