Skip to content

Instantly share code, notes, and snippets.

@debabrata100
Created June 1, 2020 18:46
Show Gist options
  • Save debabrata100/d1df9386305a95a64600440043e9a161 to your computer and use it in GitHub Desktop.
Save debabrata100/d1df9386305a95a64600440043e9a161 to your computer and use it in GitHub Desktop.
How to upload multiple images and store base 64 urls in a React State
import React, { Fragment, useRef, useState } from 'react';
const previewStyle = {
flexFlow: 'row wrap',
marginTop: '24px'
}
const imgStyle = {
height: '100px',
marginRight: '16px'
}
function readmultifiles(files, cb) {
let urls = [];
const reader = new FileReader();
function readFile(index) {
if( index >= files.length ) return cb(urls);
const file = files[index];
reader.onload = function(e) {
const bin = e.target.result;
urls = [...urls,bin]
readFile(index+1)
}
reader.readAsDataURL(file);
}
readFile(0);
}
export default () => {
const [files, setFiles] = useState([]);
const fileRef = useRef(null);
const onChange = (e) => {
const allFiles = fileRef.current.files;
readmultifiles(allFiles,function(urls){
setFiles(urls);
})
}
return (
<Fragment>
<h2>File Upload</h2>
<input
type="file"
multiple={true}
name="[]"
onChange={onChange}
ref={fileRef}
/>
<div style={previewStyle}>
{
files.length > 0 && files.map((file,i)=>(
<img key={i} style={imgStyle} src={file} alt={`prev- ${i}`} />
))
}
</div>
</Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment