Before the file upload process is finished, the progress of tracking Angular files reaches 100%

I am currently developing a service that is responsible for uploading a list of files to a backend server.

createFiles(formData: any, userToken: string): Observable<any> {
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + userToken});
    const filesUrl = this.constants.HOST_URL + 'files';
    return this.http.post(
        filesUrl, formData,
        {
            headers: headers,
            reportProgress: true,
            observe: 'events'
        }
    )
    .pipe(
        catchError(this.handleError)
    );
}

This particular service can be utilized within a component in the following manner:

export interface Upload {
    content: any | null;
    progress: number;
    state: 'PENDING' | 'IN_PROGRESS' | 'DONE';
} 

upload: Upload;

constructor( private fileService: FileService,) {}

this.fileService.createFiles(this.formData, this.token)
    .subscribe(
        (event: HttpEvent<any>) => {
            switch (event.type) {
                case HttpEventType.Sent:
                    this.upload = {content: null, progress: 0, state: 'PENDING'};
                    break;
                case HttpEventType.UploadProgress:
                    this.upload = {
                        content: null,
                        progress: Math.round((event.loaded / event.total) * 100),
                        state: 'IN_PROGRESS'
                    };
                    console.log(this.upload.progress);
                    break;
                case HttpEventType.Response:
                    this.upload = {
                        content: event.body,
                        progress: 100,
                        state: 'DONE'
                    };
                    console.log(this.upload.state);
                    break;
                default:
                    this.upload = {
                        content: null,
                        progress: 0,
                        state: 'PENDING'
                    };
            }
            if (this.upload.state === 'DONE') {
                this.files = this.upload.content;
            }
        }, error => {
            this.errorMessage = <any>error;
            console.log(this.errorMessage);
        }
    );
}

In the component's template, there is a progress bar that visually represents the upload progress:

<mat-progress-bar [mode]="upload?.state == 'PENDING' ? 'buffer' : 'determinate'"
    [value]="upload?.progress">
</mat-progress-bar>

A common issue encountered during large file uploads is that the progress bar quickly moves from 0 to 100, then tends to stay at 100 for an extended duration before transitioning to the DONE status.

An observation from the logs indicates a significant delay between the last UploadProgress event and the subsequent Response event triggering the DONE state in the Upload object.

https://i.sstatic.net/5lHXj.png Despite referencing Angular's official guides, I still find myself perplexed on how to synchronize the progress visualization with the actual upload status.

Answer №1

I have identified the source of the issue. I had overlooked the fact that this was a development environment, and the files were being transferred to a local server before being saved to a remote storage service. The rapid progress from 0-100% indicates the files are being uploaded to the local server. The delay following completion of the upload process signifies the time it takes for the local development backend server to save the files to the remote service. Fortunately, the code is functioning properly. In light of existing answers addressing how to monitor FormData upload progress, I am recommending the closure of this question as a duplicate.

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

I'm struggling to get a specific tutorial to work for my application. Can anyone advise me on how to map a general URL to the HTTP methods of an API endpoint that is written in C

I am struggling to retrieve and display data from a C# Web API using Typescript and Angular. As someone new to Typescript, I followed a tutorial to create a service based on this guide: [https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest- ...

I'm having trouble getting systemjs to properly connect and download my latest module

Recently, I developed an Angular module that is being downloaded via npm as a private node module in our company registry. Despite setting the default extension to js, my systemjs keeps searching for it in my current directory with any extension. ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Guide to enabling cross-domain uploads of files

After following a tutorial, I successfully implemented an HTML5 uploader on my website. The source of the tutorial can be found here: The uploader works perfectly; however, I am now facing an issue where I want to upload files to a different domain. Accor ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Tips for utilizing node.io for HTML parsing with node.js?

Struggling to utilize node.io with node.js for parsing an HTML page stored as a string in a variable. Encountering difficulties passing the HTML string as an argument to my node.io job. Snippet from my node file nodeiotest.js: var nodeIOJob = requi ...

The reason behind Node.js using 7 threads per process

Upon starting a Node.js process, the top command displays 7 threads connected to the process. What exactly are these threads responsible for? Furthermore, as the workload on the API rises and request handlers start asynchronously waiting for other upstre ...

Encountering build errors while utilizing strict mode in tsconfig for Spring-Flo, JointJS, and CodeMirror

While running ng serve with strict mode enabled in the tsconfig.json, Spring-Flow dependencies are causing errors related to code-mirror and Model. https://i.sstatic.net/KUBWE.png Any suggestions on how to resolve this issue? ...

What methods are available for transferring information between nodejs and puppeteer?

Recently, I developed a nodejs application that kicks off from index.js. Within index.js, puppeteer is launched and bot.js is injected into a headless-api page using the addScriptTag function. In my implementation, index.js sets a cookie to pass initial v ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

How can you extract the text content within component tags that is neither a component nor an HTML tag?

For illustration purposes, consider the following example: var ItemComponent = ng.core.Component({ selector: "item", inputs: ["title"], template: "<li>{{title}} | <ng-content></ng-content></li>", }).Class({ construc ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

Expanding the size of a Three.js geometry in one direction

I've been experimenting with scaling geometries on the y-axis, but I've run into an issue where my cube scales both up and down. I found that using mesh.transformY to animate the cube up by half of the scaling value can create the illusion of the ...

Is there a way to apply the same technique to a dynamic select option in Angular?

My array is dynamic and has an onChange method in the select option. The issue arises when I add a new array and select the new option, as it causes the first array to reset. Here's a snippet of my array structure: <ng-container formGroupName=&qu ...

How to access v-model from a separate component in Vue.js

How can I access a v-model that is located in a different component? The search field is within the App.vue file and I am trying to activate the :search='search' property in the Datatable.vue component. Code in App.vue: <v-text-field ...

Is Jquery Mobile's Table lacking responsiveness?

I have implemented a basic table from the jQuery Mobile website on my page. Take a look at the HTML code below: <div data-role="page" id="mainPage"> <div data-role="content> <table data-role="table" id="my-table" da ...

Utilizing the `useNavigate` function from react-router v6 within a class component to navigate and manage

I have a situation where I need to redirect a class component to another page. To achieve this, I came up with a function that decorates the export of the class component in order to navigate within the component's state. import { useNavigate } from & ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...