A guide to setting a file size limit for image uploads (e.g. limiting to 2MB) using Angular

We are currently working on implementing a maximum size limit of 2mb for images using ng2-file-upload. Below is the code snippet:

uploader: FileUploader = new FileUploader({
    url: URL,
    disableMultipart: true
  });
...
...
OnFileSelected(event) {
    const file: File = event[0];

    this.ReadAsBase64(file)
      .then(result => {
        this.selectedFile = result;
      })
      .catch(err => console.log(err));
  }

  Upload() {
    if (this.selectedFile) {
      this.usersService.AddImage(this.selectedFile).subscribe(
        data => {
          this.socket.emit('refresh', {});
          console.log(data);
        },
        err => console.log(err)
      );
    }
  }

  ReadAsBase64(file): Promise<any> {
    const reader = new FileReader();
    const fileValue = new Promise((resolve, reject) => {
      reader.addEventListener('load', () => {
        resolve(reader.result);
      });

      reader.addEventListener('error', event => {
        reject(event);
      });

      reader.readAsDataURL(file);
    });

    return fileValue;
  }

We are looking for guidance on where and how to enforce the image size limit. Any suggestions?

Answer №1

As outlined in the W3 documentation:

When utilizing the readAsDataURL() read method, the result attribute should provide a DOMString that represents a Data URL [RFC2397] encoding of the File or Blob's data.

Therefore, your reader.result can either be null or a DOMString. A DOMString is essentially a string composed of 16-bit characters.

To conduct a size check, you should follow these steps:

  1. Firstly, verify if reader.result is null. In case it is, proceed to throw an error or reject the Promise.

  2. Determine the length of your string considering each character as occupying 2 bytes.

  3. If the length*2 exceeds 2^20 (which equates to 2MB worth of bytes), raise an error.

The next step involves translating this into code:

  ReadAsBase64(file): Promise<any> {
    const reader = new FileReader();
    const fileValue = new Promise((resolve, reject) => {
      reader.addEventListener('load', () => {
        const result = reader.result as DOMString;
        if (!result) reject('Cannot read variable');
        if (result.length * 2 > 2**21) reject('File exceeds the maximum size'); // Note: 2*2**20 = 2**21 
        resolve(reader.result);
      });

      reader.addEventListener('error', event => {
        reject(event);
      });

      reader.readAsDataURL(file);
    });

    return fileValue;
  }

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

Reactive property in the Vue composition API

Within a Vue 3 project that utilizes TypeScript, there are two properties named locale and content: <script setup lang="ts"> import { computed, ref } from 'vue' import { useI18n } from "vue-i18n" import { Landing, Local ...

Angular outputting a basic static value

After searching extensively for a solution to my issue with Angular output, I have only come across ways to emit events. In my specific scenario, I have a parent component containing a router, and I need to dynamically change the title based on a value f ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

When an email link is clicked in Angular, Internet Explorer is automatically logged out and needs to be refreshed

I'm currently working on a project using an Angular 4 Application. One of the elements in my HTML code is an href link that has a mailto: email address. The issue I'm facing is that when I click on this link while using IE11, either I get autom ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

Analyzing different kinds of inputs received by a function

Let's say we have the following abstractions for fetching data from an API: Data storage class class DataItem<T> { data?: T | null } Query function function queryData ( fn: () => Promise<any> item: DataItem<any> ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

Sharing API types from a NestJs backend to a Vue frontend (or any other frontend) application: Best practices

In my development setup, I have a VueJs and Typescript Front End app along with a PHP server that is in the process of being converted to NestJs. Both of these projects reside in the same Monorepo, allowing me to share types for DTOs between them. I am ex ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Extension for VS Code that displays the properties of a model

Is there a VS Code extension available that allows me to view the properties of a model directly from the HTML markup? For instance, when typing ngModel and then pressing the dot (.) key, it would display its properties similar to how it works in a TypeScr ...

Anticipating outcome in NgRx Effects

Incorporating ngrx-effects into my project has been successful for retrieving data: component dispatches action -> effect triggers http service call -> data is returned from http service -> effect sends data to store through action -> component ...

What is the best way to navigate a link in Angular (15) that requires multiple parameters to be input?

I came across the following link: "https://api.api-soccer.com/v1/championship/10/stages/168" My goal is to access the data within the ID /168, but I first need to access the ID at /10. Unfortunately, I'm unsure of how to achieve this using Angular. ...

Getting the readonly-item type from an array in TypeScript: A step-by-step guide

Is it possible to create a readonly item array from a constant array? const const basicValueTypes = [{ value: 'number', label: 'Number' },{ value: 'boolean', label: 'Boolean' }]; type ReadonlyItemArray = ??? ...

Managing sessions between Node.js and Angular with JSON Web Tokens

I am currently developing an application where NodeJS serves as the backend, handling all business logic and exposing JSON REST services for consumption by the Angular 4 app which acts as a simple client. While this setup seems to be working well, I am fac ...

Angular - handling Observable<T> responses when using Http.post

One issue I encountered was when trying to implement a method that returns an Observable. Within this method, I utilized http.post to send a request to the backend. My goal was to store the JSON object response in an Observable variable and return it. Howe ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

Steps to eliminate the typescript template from create-react-app

Initially, I decided to incorporate TypeScript into my React project, which led me to run the command npx create-react-app my-app --template typescript. However, now I'm looking for a way to revert back and remove TypeScript from my setup. Is there a ...

Ionic 5 Error: Unable to access 'subscribe' property of undefined object

Working with IONIC 5 service: import { HttpClient } from '@angular/common/http'; . . . getPlaces(placeId: string) { return this.httpClient.get( `https://test.com/offered-place/${placeId}.json`) } . . . Encountering an issue when tryin ...

Transferring various sets of information into a single array

In an attempt to generate JSON data in an array for passing to another component, I followed a method outlined below. However, being relatively new to this field, my execution may not have been optimal as expected. employeeMoney: any[] = []; employeeId: an ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...