I'm trying to upload multiple images in React (nextjs) from <input onChange={onChange} type='file' name='file' multiple/>
But which way is more proper to do it? Some hours of googling didn't helped me
This is my approach(that ofc doesn't work, otherwise i would not have to write it):
I stored images' srcs using useState hook:
const [imgsSrc, setImgsSrc] = useState([])
And this is my "input on change handler":
const onChange = (changeEvent: any) => {
for (let file of changeEvent.target.files) {
setTimeout(() => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => { setImgsSrc([...imgsSrc, reader.result]) }
reader.onerror = () => { console.log(reader.error)}
}, 1000)
}
}
My input
one more time
<input onChange={onChange} type='file' name='file' multiple/>
And my way to trying to show images to user
{ imgsSrc.map((link) => { <img src={link}/> }) }
But it doesn't show me anything, so i have couple of questions that my nerve cells would be happy to get an answer to
- why it doesn't work
- does "saving images to
public
folder in root app directory" a good approach to save images - can i store base64 encode URLs remotely and get it every request, decode it and get an image
please...