I have a form to upload images and store them in localStorage with base64, then display them on the page by calling the element. When I load the images alone by clicking on the label (Since the input has a display none by CSS) EVERYTHING works perfectly, the problem is when I do an onDrop, the console tells me the following errors:
Uncaught TypeError: Cannot read properties of undefined (reading '0')
if in the onDrop I remove the [0] from the e.target.files...I get the following error
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
when the code is as follows:
// LOAD IMAGE FUNCTION
const handleImage = (files) => {
const fileReader = new FileReader();
fileReader.onloadend = () => {
if (fileReader.readyState === 2) {
setForm({ ...form, backdrop_path: fileReader.result });
}
};
fileReader.readAsDataURL(files);
setImage(true)
return image
};
// This function submits the form, it is the button function
const onSubmit = (e) => {
e.preventDefault();
const { title, backdrop_path } = form;
if (title === '' || backdrop_path === '') return;
const movie = {
title,
backdrop_path,
};
localStorage.setItem('MyUploadedMovies', JSON.stringify(movie));
setFormComplete(true)
};
//FUNCION REACT ONDROP
const handleDragOver = (event) => {
event.preventDefault()
}
const handleDrag = (evt) => {
console.log(evt.currentTarget.id)
}
// This is the section that accepts the image in the form
{ image ?
<ProgressBar/>
:
<div className='fileImgContainer'
draggable={true}
onDragOver={handleDragOver}
onDragStart={handleDrag}
onDrop={(e) => handleImage(e.target.files[0])}
>
<label htmlFor="imgfiles" className='fileImgLabel'>
Agregá un archivo o arrastralo y soltalo aquí
</label>
<input
className='fileImgInput'
id='imgfiles'
type='file'
defaultValue=''
accept='image/png,image/jpeg'
onChange={(e) => handleImage(e.target.files[0])}
/>
</div>
}
I want to clarify that I am NOT using ANY library
const handleDrop = (ev) => {
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (let i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
const file = ev.dataTransfer.items[i].getAsFile();
handleImage(file)
}
}
} else {
// Use DataTransfer interface to access the file(s)
for (let i = 0; i < ev.dataTransfer.files.length; i++) {
handleImage(ev.dataTransfer.files[i])
}
}
}