In this article, we will see how to upload and preview images in react js. You can learn how to show an image preview before uploading it to the server in a react js. If you want to show a preview of the image before uploading it into your react app. So, we will create a simple react js app that will use an HTML file input field along with some events to show an image preview. For the backend, we will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload an image.
So, let's see react js image upload with preview and react js image upload with preview display.
Step 1: Create React App
Step 2: Install Axios and Bootstrap 4
Step 3: Create Simple Image Upload with Preview Component
Step 4: Add Component in App.js
Step 5: Create PHP File
In this step, we will create a new react app using the following command.
npx create-react-app my-react-app
To run the react app, execute the following command on your terminal.
npm start
In this step, we will install bootstrap 4 libraries into react app.
npm install bootstrap --save
npm install axios --save
Add bootstrap.min.css file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>How To Upload And Preview Image In React JS - Websolutionstuff</h2>
</div>
);
}
export default App;
In this step, we will create the ImageUploadPreviewComponent.js component.
import React, { Component } from 'react';
import axios from 'axios';
class ImageUploadPreviewComponent extends Component {
constructor(props) {
super(props)
this.state = {
file: null
}
this.uploadSingleFile = this.uploadSingleFile.bind(this)
this.upload = this.upload.bind(this)
}
uploadSingleFile(e) {
this.setState({
file: URL.createObjectURL(e.target.files[0])
})
}
upload(){
const formData = { image: this.state.file }
let url = "http://localhost:8000/upload.php";
axios.post(url, formData, { // receive two parameter endpoint url ,form data
})
.then(res => { // then print response status
console.warn(res.data);
})
}
render() {
let imgPreview;
if (this.state.file) {
imgPreview = <img src={this.state.file} alt='' />;
}
return (
<form>
<div className="form-group preview">
{imgPreview}
</div>
<div className="form-group">
<input type="file" className="form-control" onChange={this.uploadSingleFile} />
</div>
<button type="button" className="btn btn-primary btn-block" onClick={this.upload}>Upload</button>
</form >
)
}
}
To upload the file you need an HTML template. In this template, you will create a `file input` element that allows us to choose the file and a button to upload a file. So, defined the if statement inside the render() method.
Note: The `uploadSingleFile` method will be called when the user chooses a file. It will get the file object of the selected file and store it in the `file` state. And will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload the image to the server.
In this step, we will add the ImageUploadPreviewComponent.js file in src/App.js
file.
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ImageUploadPreviewComponent from './ImageUploadPreviewComponent'
function App() {
return (
<div className="App">
<ImageUploadPreviewComponent/>
</div>
);
}
export default App;
In this step, we will create a PHP file, which names upload.php. And add the following code to it.
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// Folder Path For Ubuntu
// $folderPath = "/var/www/my-app/uploads";
// Folder Path For Window
$folderPath = "uploads/";
$file_tmp = $_FILES['image']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['image']['name'])));
$file = $folderPath . uniqid() . '.'.$file_ext;
move_uploaded_file($file_tmp, $file);
return json_encode(['status'=>true]);
?>
- Read Also: How To Use Array In React JS
- Read Also: How To Install React JS Step By Step
- Read Also: How To Upload Multiple Image In Laravel 9
- Read Also: How To Preview Image Before Upload In jQuery