April 4, 2020

File uploading in React.js

The process of uploading an image can be broadly divided into two steps:

  • Select a File (user input): To enable the user to pick a file, the first step is to add the tag to our App component. This tag should have the type attribute set as “file”. Now, we need an event handler to listen to any changes made to the file. This event handler will be triggered whenever the user selects a new file and will update the state.
  • Send a request to the server: After storing the selected file (in the state), we are now required to send it to a server. For this purpose, we can use fetch or Axios. (In this code, we use Axios a promise-based HTTP client for the browser and NodeJS). The file is sent to the service wrapped in a FormData object.
To get in-Depth knowledge on Reactjs you can enroll for a live demo on Reactjs Online Training

Installation Axios:

  • Run the below command
npm install axios --save


// 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 
	// Details of the uploaded file 
	// 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 ( 
			<h2>File Details:</h2> 
			<p>File Name: {this.state.selectedFile.name}</p> 
			<p>File Type: {this.state.selectedFile.type}</p> 
			Last Modified:{" "} 
	} else { 
	return ( 
			<br /> 
			<h4>Choose before Pressing the Upload button</h4> 
	render() { 
	return ( 
			Reactjs online Training
			File Upload using React! 
				<input type="file" onChange={this.onFileChange} /> 
				<button onClick={this.onFileUpload}> 
export default App;