In this article, we will see how file uploads in react js. File uploading means a user from a client machine wants to upload files to the server. We will see file uploading using react js. In this example, we will see the single file upload in react. Also, we will use Axios for image upload.
So, let's see react js file upload and how to upload a file in react js.
The process of uploading a file can be divided into two steps.
In this step, we will install Axios using the following command for react upload file.
npm install axios --save
After installing Axios, we will see an example of react file upload.
import axios from 'axios';
import React,{Component} from 'react';
class App extends Component {
state = {
// Initially, no file is selected
selectedFile: null
};
// On file select (from the pop up)
onFileChange = event => {
// Update the state
this.setState({ selectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.selectedFile,
this.state.selectedFile.name
);
// Details of the uploaded file
console.log(this.state.selectedFile);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
};
// File content to be displayed after
// file upload is complete
fileData = () => {
if (this.state.selectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>File Name: {this.state.selectedFile.name}</p>
<p>File Type: {this.state.selectedFile.type}</p>
<p>
Last Modified:{" "}
{this.state.selectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose before Pressing the Upload button</h4>
</div>
);
}
};
render() {
return (
<div>
<h1>
How To File Upload In React JS - Websolutionstuff
</h1>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>
Upload!
</button>
</div>
{this.fileData()}
</div>
);
}
}
export default App;
You might also like:
In this article, we will see how to check password strength using jquery. here we will check whether password ...
Sep-04-2020
Here we will see how to generate dynamic sitemap in laravel. As we know sitemap is very important part of seo, sitemap i...
Jul-05-2021
In this article, we will see how to create a candlestick chart in laravel 9 using highcharts. A candlestick is a ty...
Oct-06-2022
In this article, how to send email in laravel 9 using mailgun. we will learn laravel 9 to send emails using mailgun...
Jul-29-2022