In my Next.js application, I am attempting to allow users to upload an image from their system using an input field of type "file" and then read the content of the file using FileReader().
const OnChange = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
console.log([file, reader, reader.result]);
reader.onload = () => {
console.log("hello");
if (reader.readyState === 2) {
setAvatarPreview(reader.result);
}
setAvatar(file);
reader.readAsDataURL(file);
};
reader.onerror = function (event) {
console.log("Error reading file:", event.target.error);
};
};
// this is jsx
<form className="mt-4 p-2 flex items-center justify-center border-2 border-black">
<input
type="file"
name="avatar"
id="avatar"
onChange={OnChange}
accept="image/*"
/>
</form>
The issue I am facing is that the onload event listener is not being triggered.
Despite ensuring that the uploaded file is of the correct image type (jpg, png), the onload or any other event listeners are not being fired to read the content of the file.