What could be the reason for the HttpEventType.UploadProgress event only triggering once during an Angular file upload request?

I am currently working on implementing file uploads in Angular and am looking to display the upload progress as well.

upload.service.ts

public uploadProductImage(obj: FormData, id: string) {
    return this._http.post(baseUrl + `/product/upload`, obj, {
      headers: {
        product_id: id,
      },
      reportProgress : true,
      observe : 'events'
    });
  }

upload.component.ts

uploadClick() {
    const fd = new FormData();

    // for(const f of this.file_url) {
    //   fd.append('image', f.file, f.file.name);
    // }
    fd.append('image', this.file_url[0].file, this.file_url[0].file.name);
    this.service.uploadProductImage(fd, this.product_id.toString())
      .subscribe(
        event => {
          if (event.type === HttpEventType.UploadProgress) {
            console.log(event.loaded, event.total);
            this.progress = Math.round(event.loaded / event.total * 100);

          } else if (event.type === HttpEventType.Response) {
            console.log(event.body);
            this.file_url = [];
          }

        },
        err => {
          console.log(err);
        }
      );
  }

The image uploading functionality is now up and running smoothly. However, the progress bar feature seems to be experiencing some glitches. I am receiving one event with HttpEventType.UploadProgress immediately, with both event.loaded and event.total values being equal.

As a result, the progress bar jumps to 100 immediately, even though there is a delay in completing the request.

Answer №1

I encountered a similar problem when my server was on localhost, leading to immediate uploads with progress always showing 100%. To experience a more realistic upload progress, try throttling the request in Chrome.


Here's how you can throttle the network in Chrome:

  1. Open DevTools by pressing F12
  2. Go to the 'Network' tab
  3. Select the type of connection you wish to mimic (choose 'Slow 3G' for accurate results)

Answer №2

I've successfully implemented this code snippet in a recent project. It's functioning as expected, and I believe it could be beneficial for your use case as well.

import { HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';


handleFileUpload() {
        const formData: FormData = new FormData();
        formData.append('file', this.selectedFile);

        const request = new HttpRequest('POST', apiUrl, formData, {
          reportProgress: true,
        });

        this.http.request(request)
        .subscribe(
          (event) => {
            if (event.type === HttpEventType.UploadProgress) {
              // Processing and displaying upload progress percentage:
              this.uploadPercentage = Math.round(100 * event.loaded / event.total);
              console.log(`File upload progress: ${this.uploadPercentage}%`);
            } else if (event instanceof HttpResponse) {
              console.log('File upload completed successfully!');
              console.log(event.body);
            }
          },
          error => console.error(error)
        );
}

Answer №3

Dealing with a similar problem, I discovered that the culprit was a custom HttpInterceptor that utilized the toPromise method:

intercept(req: HttpRequest<any>, next: HttpHandler): any {
    return from(this.handle(req, next));
}

private async handle(req: HttpRequest<any>, next: HttpHandler) {
  try {
      return await next.handle(req).toPromise();
  } catch (err: any) {
      // error-handling logic
  }
}

By making the following adjustments to the code:

intercept(req: HttpRequest<any>, next: HttpHandler){
    return next.handle(req)
      .pipe(catchError(err => {
        // error-handling logic
        return throwError(err);
      }));
  }

I was able to successfully resolve the issue.

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

What could be the reason for the failure of Angular Material Table 2 selection model?

A Question about Angular Mat Table 2 Selection Model Why does the selection model in Angular Mat Table 2 fail when using a duplicate object with its select() or toggle() methods? Sharing Debugging Insights : Delve into my debugging process to understand ...

Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker. I noticed a peculiar difference in behavior with the import statement between the two setups. The issue arises with the second impo ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

How can I enable autofocus on a matInput element when clicking in Angular 6?

Is there a way to set focus on an input element after a click event, similar to how it works on the Google Login page? I've tried using @ViewChild('id') and document.getElementId('id'), but it always returns null or undefined. How ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Modifying PDF files using Angular 4

Encountering a CORS problem in node v8.9.4. Error message - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200& ...

Error in Vue 3 Script Setup with Typescript: Implicit 'any' type for parameter 'el' in Template ref

Could someone help explain why I am receiving an error from TypeScript that says the following? error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)". I am confident that the correct type is set ...

The child component stays consistent across all Angular routing configurations

Currently diving into Angular routing, I've added two routerLinks to the parent component. It appears that routing is set up correctly, but for some reason the page remains unchanged. Parent Child const childrenRoutes: Routes =[ {path: 'overvi ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Develop a TypeScript class by incorporating a static function from an external library, while ensuring type safety

I am looking to enhance the capabilities of the rxjs5 Observable class by adding a static function. While this can be easily accomplished in plain JavaScript: var myStaticFn = function() { /* ... */ }; Observable.myStaticFn = myStaticFn; this approach w ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Ways to incorporate a notification feature with an icon or image

I'm looking to create a visually dynamic icon/image similar to mobile device notifications, but primarily for desktop use. This image will be positioned before some text. For instance: https://i.sstatic.net/MHocy.pngSome Text This design features tw ...

The automatic inference of function argument types and the implementation of conditional types

I'm facing a specific scenario: There's a function that takes in a boolean and returns either a RealItem or an ImaginaryItem. I'm using conditional types to determine the return type based on the boolean argument. type RealItem = { color: s ...

Manipulating a MongoDB object using node.js

Within my server.js file, I have defined a database model to be used for a POST request: var department = mongoose.model('department', { departmentName: String, rooms: [{ roomNumber: String, width: Number, height: Number, pos ...

Mastering the implementation of type refinements for io-ts in processing input data

I have implemented io-ts for defining my typescript types. This allows me to perform runtime type validation and generate type declarations from a single source. In this particular scenario, I aim to create an interface with a string member that needs to ...

How to deactivate Kendo Dropdownlist in Angular 2

Currently, I am attempting to disable a kendo-dropdownlist (named ddlChargeType). The goal is to prevent the user from manually selecting a value, while still allowing for programmatic selection (such as when a valid option is chosen in another dropdown, ...

Challenge encountered when utilizing angular 2 RC router for programmatic route navigation

Currently, I am utilizing the RC router in version rc1 with two defined routes as shown below: @Routes([ {path: '/', component: HomeComponent}, {path: '/signin', component: SigninComponent}, {path: '/dashboard', c ...

Successfully generated files, now patiently awaiting typecheck results... encountering an issue with importing SASS modules

Issue Encountering a problem where adding SASS variables to TypeScript files causes the browser tab with an open devserver to hang, displaying Files successfully emitted, waiting for typecheck results.... Trying to figure out what's causing this iss ...