Image upload in ReactJS
As you know the file upload is a very important feature of the web application, It help us to upload files/images to the server. So today I am going to show you how to upload file/image using ReactJS.
Image upload in ReactJS, File upload in React JS, Reactjs nodejs upload image, React Image Preview & Upload, Step by step tutorial to upload file/image using ReactJS & Node.js with example, react image upload demo.
Checkout more articles on ReactJS:
- Form validation in ReactJS
- Copy text to the Clipboard in ReactJS
- Nested Routes in React JS
- API call in React JS
We can divide this article in two steps.
- Select the file/image
- Send it to a server
So here we will create UI in ReactJS application and use the Node.js as server to store the uploaded file.
Way to implement Image upload in ReactJS
- Create server/API to handle the uploaded file
- Setup react application
- Design the HTML
- Upload file to a server
- Output
1. Create server/API to handle the uploaded file
As we are planning to upload image via React application, So we need server support in form of API to upload image to a server. For that we have to create the file upload API in Node.js. Please refer below link if you don't know about it.
2. Setup react application
First, Let's setup the simple react application to implement the upload functionality. Following link will help you to create basic react application.
3. Design the HTML
Basically we will have following component in HTML.
- Input file to allow the user to pick a file. We also have to listen to any changes to that file. Such a change handler will trigger whenever the user picks a new file.
- Button to send choosen file to a server via an API call.
- Image tag to display the uploaded image on the page.
- Label to display file upload API response message on the page.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null, // to store selected file
handleResponse: null, // handle the API response
imageUrl: null // to store uploaded image path
};
}
// handle change event of input file
onChangeFile = event => {
this.setState({ selectedFile: event.target.files[0] })
}
// handle click event of the upload button
handleUpload = () => {
console.log('selectedFile: ', this.state.selectedFile);
}
render() {
const { handleResponse, imageUrl } = this.state;
return (
<div className="App" >
<h4>Image Upload in ReactJS - Clue Mediator</h4>
<p className="title">Select Image:</p>
<div style={{ marginBottom: 10 }}>
<input type="file" onChange={this.onChangeFile} />
</div>
<input type="button" value="Upload" onClick={this.handleUpload} />
{handleResponse && <p className={handleResponse.isSuccess ? "success" : "error"}>{handleResponse.message}</p>}
<p className="title" style={{ marginTop: 30 }}>Uploaded Image:</p>
{imageUrl && <img src={imageUrl} alt="Uploaded File" height="100" width="100" />}
</div>
);
}
}
export default App;
4. Upload file to a server
Now it's time to integrate the API and call it on button click handler. For that, we'are using the axios package to send image in a FormData object. It depends on what your REST API expects.
import React, { Component } from 'react';
import axios from 'axios';
// base url of API
const BASE_URL = 'http://localhost:4000/';
class App extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null, // to store selected file
handleResponse: null, // handle the API response
imageUrl: null // to store uploaded image path
};
}
// handle change event of input file
onChangeFile = event => {
this.setState({ selectedFile: event.target.files[0] })
}
// handle click event of the upload button
handleUpload = () => {
const { selectedFile } = this.state;
if (!selectedFile) {
this.setState({
handleResponse: {
isSuccess: false,
message: "Please select image to upload."
}
});
return false;
}
const formData = new FormData();
formData.append('dataFile', selectedFile, selectedFile.name);
axios.post(BASE_URL + 'uploadfile', formData).then(response => {
this.setState({
handleResponse: {
isSuccess: response.status === 200,
message: response.data.message
},
imageUrl: BASE_URL + response.data.file.path
});
}).catch(err => {
alert(err.message);
});
}
render() {
const { handleResponse, imageUrl } = this.state;
return (
<div className="App" >
<h4>Image Upload in ReactJS - Clue Mediator</h4>
<p className="title">Select Image:</p>
<div style={{ marginBottom: 10 }}>
<input type="file" onChange={this.onChangeFile} />
</div>
<input type="button" value="Upload" onClick={this.handleUpload} />
{handleResponse && <p className={handleResponse.isSuccess ? "success" : "error"}>{handleResponse.message}</p>}
<p className="title" style={{ marginTop: 30 }}>Uploaded Image:</p>
{imageUrl && <img src={imageUrl} alt="Uploaded File" height="100" width="100" />}
</div>
);
}
}
export default App;
Make sure your Node.js server is enabled to hit the API from ReactJS.
5. Output
Output - Image upload in ReactJS - Clue Mediator