Verifying Image Sizes in Angular 7

There are numerous solutions available for this question regarding usage of JQuery, JavaScript, and various versions of Angular.

I have attempted multiple solutions but none seem to be working for me.

Currently, I am utilizing Angular 7 and attempting to validate the uploaded image's Width and Height provided by the user.

Below is a snippet of my .html code:

<input type="file" name="upload" id="androidPhoneFile" class="upload-box" placeholder="Upload File" multiple="multiple" (change)="onAndroidPhoneChange($event)" formControlName="androidPhone" #androidPhonePhoto>

And here is a section from my .ts component file:

AddFilesToFormData(event: any, fileName: string) {
const reader = new FileReader();
const img = new Image();
img.onload = function() {
  const height = img.height;
  const width = img.width;
  console.log('Width and Height', width, height);
};

img.src = event.target.files[0];
if (event.target.files && event.target.files.length) {
  const [file] = event.target.files;
  reader.readAsDataURL(file);
  reader.onload = () => {
    for (let i = 0; i < event.target.files.length; i++) {
      this.formData.append(fileName, event.target.files[i]);
      this.numberOfPhotos++;
    }
  };
}}

Answer №1

Consider trying out this approach:


AddFilesToFormData(event: any, fileName: string) {
  if (event.target.files && event.target.files.length) {
    for (const file of event.target.files) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const img = new Image();
        img.src = reader.result as string;
        img.onload = () => {
          const height = img.naturalHeight;
          const width = img.naturalWidth;
          console.log('Width and Height', width, height);
        };
      };
    }
  }
}

In regards to the for loop: I suggest updating it as follows:

    for (const image of event.target.files) {
      this.formData.append(fileName, image);
      this.numberOfPhotos++;
    }

This modification enhances clarity in your code.

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

Deleting a parent item along with its child elements in the ngrx state management library

I am currently exploring ngrx store and grappling with where to place my logic, specifically whether looping through an array should be handled in the reducer or the component. I have an array of objects called Item that need to be manipulated - particular ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

Unable to disable the rule explicit-function-return-type in ESLint while performing TypeScript linting

I am currently utilizing: ESLint version 7.5.0 - operating through the command line for Angular files TypeScript-eslint/eslint-plugin version 3.7.0 TypeScript-eslint/parser version 3.7.0. Despite having the rule '@typescript-eslint/explicit-function- ...

The toggle button appears to be lacking in CSS styling

I'm trying to create a dropdown button using Bootstrap and ng-bootstrap in my Angular project. Here's the HTML I've written: <div ngbDropdown class="d-inline-block"> <button class="btn btn-outline-primary" id="dropdownBasic1" n ...

Sharing Array Data Between Child Components in Angular Using TypeScript

I've been attempting to pass an array from one child component to another without success. Despite following various online tutorials on using a service to share data, my page fails to load anything. The issue that was causing problems in my program ...

Jest encountered an UnhandledPromiseRejection error because the promise was unexpectedly resolved instead of being rejected

I am facing a difficult error message from Jest that I can't seem to figure out. The error message indicates that the promise is being resolved instead of rejected, causing an unhandled promise rejection. It's confusing because Jest expects an er ...

Nested function TypeScript declarations

Currently, I am attempting to define a type for my controller function in (nodejs) similar to the following export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) { res.status(200).json({ success: true}); }) ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Creating a TypeScript function definition that adapts dynamically based on the input functions

Is it feasible to alter the type of something depending on the value of an argument passed to a function? I am in need of this specific type for an event emitter with callback. For instance: interface IUser { name: string } type CallbackType = /* A dyna ...

"JavaScript/TypeScript: The Importance of Defining Object Return Types

While going through the Tour of Heroes tutorial for Angular, I found this method of returning an object to be confusing. createDb() { const heroes = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: &a ...

Update TypeScript definitions in version 2.2.2 obtained from NPM @Types

I am currently utilizing the component react-router-bootstrap along with the definitions from DefinitelyTyped. However, the downloaded definitions do not align with the component. While I have submitted a pull request to rectify this issue, it has not yet ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

Sending image from angular2 to asp.net core server

Currently, I have an asp.net core application with angular2 and I am facing an issue with uploading images. While I was able to upload images as byte[], I encountered a problem in checking if the uploaded file is actually an image on the backend. This led ...

The required dependencies for google-chart-angular are not found

I have been trying to set up google-chart-angular in my Angular project by following the steps outlined in this tutorial. I have also added GoogleChartsModule to my app.module.ts file. Although I believe everything is set up correctly, when I try to run t ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. https://i.sstatic.net/CZTO2.png The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it s ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

Unlocking the Potential of Vue Class Components: Exploring Advanced Customization Options

Currently, I am working on a project using Vue 2 with Typescript. However, I am facing an issue where I cannot add options to the component. <script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import HelloW ...

What is the best way to generate a JSON object with Angular and showcase its content through HTML?

Currently, I am dealing with a JSON object that is completely unfamiliar to me. Without knowing the keys or values of this object, I was able to successfully manipulate it and extract the necessary information. Ultimately, I have generated an array (whic ...