The Filereader seems to be having trouble reading a specific file

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.

Answer №1

It is important to note that reader.readAsDataURL(file); should not be placed inside the reader.onload function. This is because the onload function is only triggered when one of the reader's read methods is called.

To ensure proper functionality, move reader.readAsDataURL(file) outside of reader.onerror within the OnChange function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The code is nearly identical except for one issue that causes an infinite loop within useEffect

Hey, I'm new to reactjs and I've encountered a puzzling situation with the following two code snippets. I can't figure out why using the "First code" results in an infinite loop (endless '123' log outs in my browser console) while ...

What is preventing me from assigning a value of false to my JavaScript variable?

I'm encountering an issue where the articleExists variable is not being set to true on line 6, even though I have used console logs to double check that the if statement containing it is functioning properly. app.post("/articles", function(req, res) ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

Is there a method for decreasing the expected conv2d_Conv2D1_input from 4 dimensions to 3?

Issue: An error message states that conv2d_Conv2D1_input is supposed to have 4 dimensions, but the array provided has a shape of [475,475,3] However: The inputShape is configured as [475,475,3] Upon inspection, tensors exhibit the shape [475,475,3] Err ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Make sure a div is displayed on top of any content currently in fullscreen mode

I recently encountered an issue with my Chrome extension where a menu I inserted into the page would disappear whenever a flash or html5 video player went full screen. Is it possible to have two objects in full screen simultaneously, or is there another so ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Tips for Designing a Custom Footer Layout for KoGrid

Is it possible to create a footer template for a koGrid that displays the sum of a column? gridOptions : { displaySelectionCheckbox: false, data: items, // selectedItems: self.selectedItems, multiSelect: false, ena ...

Angular sing ng-view to load images from a file

I am developing a single page app (index.html) with the following relevant sections: <!DOCTYPE html> <html> <head> <base href="/mi_ui/"> <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css"> <script s ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

Having trouble with authentication login in Next.Js 13, not working as expected

Recently, I set up a Next.Js (13.4.19) app with next-auth (4.23.1) for authentication following a tutorial on YouTube (link). I configured my auth system using only GitHub and Google providers. However, upon trying to login, the app redirects me to the co ...