article

Tuesday, April 11, 2023

React JS Multiple Image Upload with Preview

React JS Multiple Image Upload with Preview

Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start


C:\react-js\myreactdev\src\App.js
//C:\react-js\myreactdev\src\App.js
import React, { } from 'react';
import './App.css';

import ImageUploadPreview from './ImageUploadPreview'; 
function App() {  
     
  return (  
    <div className="container">  
      <ImageUploadPreview/>  
    </div>  
  );  
}  
 
export default App;
C:\react-js\myreactdev\src\ImageUploadPreview.js
//C:\react-js\myreactdev\src\ImageUploadPreview.js
import React, { Component } from "react";

export default class ImageUploadPreview extends Component {
	
 
    fileObj = [];
    fileArray = [];
	
    constructor(props) {
        super(props);
		
        this.state = {
            file: [null]
        };
		
        this.uploadMultipleFiles = this.uploadMultipleFiles.bind(this)
        this.onSubmit = this.onSubmit.bind(this)
        this.uploadFile = this.uploadFile.bind(this)
    }
 
    uploadMultipleFiles(e) {
        this.fileObj.push(e.target.files)
        for (let i = 0; i < this.fileObj[0].length; i++) {
            this.fileArray.push(URL.createObjectURL(this.fileObj[0][i]))
        }
        this.setState({ file: this.fileArray })
    }
 

	
    async onSubmit(e){
        e.preventDefault() 
        this.uploadFile(this.state.file);
        console.log(this.state.file);
    }

    async uploadFile(file){ 
        const formData = new FormData();
		console.log(formData);
    }
 
    render() {
        return (
			<div className="row">
                {(this.fileArray || []).map(url => (
					<div className="col-lg-4 col-md-12 mb-4 mb-lg-0">
                        <img src={url} alt="..." key={url} className="img-responsive rounded"/>
					</div>
                ))}
                
				<form onSubmit={ this.onSubmit } className="form-inline">
					<p><h3>React JS Multiple Image Upload with Preview</h3></p>	
					<div className="form-group">
						<input type="file" className="form-control" onChange={this.uploadMultipleFiles} multiple />
					</div>
					<div><button type="submit" className="btn btn-success" >Upload File</button></div>
				</form >
			</div>
        )
    }
}
react-js\myreactdev\src\App.css
//react-js\myreactdev\src\App.css
body {
  margin: 0;
  background-color: #ffffff;
}

.rounded {
    border-radius: var(--mdb-border-radius)!important;
}
.img-responsive {
	margin-top:10px;
}	
Run C:\react-j\myreactdev>npm start

Related Post