Created
June 1, 2020 18:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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