Guide on how to implement a file upload feature using only JavaScript and the FileReader API

Allow me to explain the issue I'm facing. To give you some context, I've been working on a forum web application. Lately, I've been trying to enable users to choose a photo from their local file system during sign up. The idea is that once a user selects an image, it should be read using the FileReader API in client-side JavaScript. Then, the selected image URL should be set as the value of the file input before submitting the form.

It's important to note that my goal is not to directly upload the file as a separate image, but rather to store the data URL in my database. While many suggest using Multer for file uploads, I've already made significant progress and pushed changes to my GitHub repository. Thus, installing new npm packages is not an option at this point.

The main issue I'm encountering is that the value of the input does not change, and the uploaded URL only shows the name of the image file (for example, shark.jfif). Despite searching online, I haven't found a solution yet. Below is my current client-side JavaScript code:

const file = document.querySelector('input[type="file"]').files[0];
const fReader = new FileReader();
const imgName = fReader.readAsDataURL(file);
document.querySelector('input[type="file"]').value = imgName.result;

Ideally, I would like to use an event listener to monitor when the input file value changes. However, I'm unsure about which event would be most suitable. Using the submit event is not ideal since the code execution takes some time, and by the time the form is submitted, only the filename is saved in the database. As of now, the value remains unchanged with my existing code.

Answer №1

A few years back, I worked on a similar project that eventually evolved into a small JavaScript 'library' known as imagecropper.js. This library offers additional features such as the ability to crop images before uploading them anywhere in the file input -> canvas -> img workflow. For the purpose of this explanation, we will focus solely on skipping the canvas step.

The main concept revolves around fetching the data URL from the FileReader and then setting it as the src attribute of the img tag:

const image = document.getElementById('image');
document.getElementById('fileUpload').addEventListener("change", e => {
  const selectedFile = e.target.files[0];
  const fileReader = new FileReader();
  
  // Reading the image as base64 data
  fileReader.readAsDataURL(selectedFile);
  
  // Once loaded, use the image data
  fileReader.onload = (e) => image.setAttribute('src', e.target.result);
});
<input type="file" id="fileUpload" />
<img id="image" src="" />

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

Creating movement in three distinct divisions

I am seeking a way to have three divs flying in upon click. The first DIV is positioned at the top, followed by one on the left and one on the right (both being below the top one). I wish for them to fly in from their respective directions - the top div fr ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

What is the reason behind the cautionary note associated with Vue's provide and inject functionality?

Considering incorporating Vue's new provide/inject feature into a project, I came across a warning in the official Vue documentation: The documentation states that provide and inject are primarily intended for advanced plugin/component library usage ...

Step-by-step guide on crafting a scrolling marquee with CSS or Javascript

I am in need of creating two marquees for a website project. The first marquee should showcase a repeating image while the second one should display links, both spanning the browser window at any size. It is crucial that the marquee items are displayed fro ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Incrementing the index in Javascript when an event occurs

I am currently working on a project that involves incrementing an index of an array based on certain events, such as a left mouse click over a designated area. The code snippet provided below initializes all values to zero and briefly changes the relevan ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

Facing an issue in React-Native where unable to navigate to the second screen

I hope you don't mind the length of my query, as this happens to be my debut here and I am really eager to unravel the mysteries surrounding my code conundrum. Your assistance in this matter would be greatly appreciated. Could someone please lend me ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Is there a way to invoke a function within an Angular Service from within the same service itself?

Below is the code snippet I am working with: angular.module('admin') .factory('gridService', ['$resource', 'gridSelectService', 'localStorageService', function ($resource, gridSelectService, ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

Displaying a particular form depending on user selection in PHP

Being new to the world of HTML and PHP, I have a question. In my HTML code, there is a form with two options to select from: lesson or topic. I want to display a different form depending on whether the user selects "lesson" or "topic." How can I achieve ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

What is the best way to exclude empty fields from an API response when using the .map() function in Nextjs

I've created a custom repository API that I want to integrate into my Next.js web application. However, if any field in the API is empty, I need to exclude that particular element. The contents of my API: { "myrepo": [ { ...

Is there a way to initiate multiple AJAX requests once a single request has been completed successfully?

I have created two functions and I want to call the get_name_from_id function when my first ajax function is successful. However, it is not working as expected. When I add an alert in the get_name_from_id function after the jsonString variable like alert ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Concealing a DIV element when the value is not applicable

I'm currently working on a website for a coffee shop product. On this site, each product has a coffee strength indicator that is determined by the database. The strength can be categorized as Strong, Medium, Weak, or n/a (for non-coffee products). If ...