What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview

Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2.

2. Initial Strategy

2.1. HTML Code

<p-fileUpload #fileUploader name="file" url="{{uploadUrl}}" accept=".jpeg,jpg" 
  auto="auto" mode="basic" chooseLabel=„Upload file“
  (onBeforeUpload)="fileUploadOnBeforeUpload($event, fileUploader)">
</p-fileUpload>

2.2. TypeScript Implementation

fileUploadOnBeforeUpload(event) {
  if (condition) {
    event.xhr.abort();
  }
}

2.3. Outcome

Method executed without errors, but failed to stop the upload process.

3. Revised Approach

3.1 TypeScript Revision

fileUploadOnBeforeUpload(event, fileUploader: FileUpload) {
  if (condition) {
    for (let file of fileUploader.files) {
      const index = fileUploader.files.indexOf(file);
      fileUploader.remove(event, index);
    }
  }
}

3.2 Result of Update

Selected files successfully removed before transfer, halting the upload process as intended. However, backend server logs a 400 error due to empty request in the browser console:

Failed to load resource: the server responded with a status of 400 ()
.

4. Ongoing Challenge

Seeking solution on how to effectively abort file uploads in PrimeNG FileUpload component after specific file selections.

Answer №1

event.xhr.abort();

This line of code is used to terminate a sent request. However, it cannot be executed within the onBeforeUpload or onBeforeSend functions, as mentioned in the documentation:

The XMLHttpRequest.abort() method terminates the request if it has already been sent.

Even if you attempt to abort the request, it will still proceed unless you specify customUpload="true" (documentation)

To resolve this issue, follow these steps:

  1. Define custom upload

    <p-fileUpload #fileUpload customUpload = "true" (uploadHandler)="handleUpload($event)">
    
  2. Implement logic in your component.ts file

     handleUpload(event: any) {
    
     // Add your desired functionality here
    
     if(condition) {
       // Ready to proceed!
       let formData = new FormData();
    
       for (let file of event.files) {
         formData.append('file', file, file.name);
       }
    
       this.sendFile(formData).toPromise().then((result: any) => {
         if(result.status == 200) { // Success
           // Implement your code: display a message, update list of files, etc.
         }
       });
     }}
    
  3. Create a function to execute the actual call

    sendFile(formData) {
         // http is HttpClient. You can customize it and include necessary authentication headers, etc.
         return this.http.post(this.HierarchyFileUploadUrl, formData);
     }
     

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

Error occurs after upgrading React app to vite due to node-fetch issue

I'm a bit perplexed by this issue. Transitioning the build tool to vite has been seamless except for encountering this error: No matching export in "node_modules/node-fetch/lib/index.mjs" for import "RequestInit" No matching expor ...

How can I make the navbar in Angular stay fixed in place?

After using the ng generate @angular/material:material-nav --name=home command to create a navbar, I am trying to make it fixed at the top while scrolling. I attempted using position: fixed; on my mat-sidenav-content but it didn't work. Does anyone ha ...

"Experiencing issues retrieving user-modified values in NativeScript's TimePicker component

I'm having trouble retrieving the user-modified value from a TimePicker. Instead of getting the modified value, I keep receiving the original value that was initially set in the control. Below is my component template: <TabView [(ngModel)]="tabSe ...

angular2 - Having trouble retrieving data from subject

Why am I unable to successfully initialize and retrieve data from a service using a subject in Angular? HomeComponentComponent.TS export class HomeComponentComponent implements OnInit { public homeSub; constructor( private subService: SubjectServ ...

Can you please provide instructions on how to obtain the TypeScript definitions file for a specific version of Jquery, such as 3.2.1

As I navigate my way through TypeScript, I find myself in need of accessing type definitions for a jQuery project in Visual Studio. The project currently utilizes jquery version 3.2.1, and I'm on the lookout for TypeScript type definitions for it. Af ...

Issues with the functionality of multiselect in Angular2-PrimeNg's reactive forms are currently being experienced

Currently, I am utilizing PrimeNG version 2.0.3 alongside Angular 2.0.0 while implementing reactive forms. My aim is to incorporate the multiselect functionality of PrimeNg into my form. To achieve this, I have taken the following steps: Component.html ...

A Guide to Retrieving Parameters and Request Body using Express and Typescript

When I use the PUT method, I encounter this issue: const createFaceList = (req: Request<{faceListId : string}>, res: Response, next: NextFunction) => { console.log(req.body.name); console.log("faceListID = " + req.params.faceListId); a ...

When it comes to form validations, I encounter an issue. I am able to view errors.minlength in the console, but for some reason, I am unable to access it

I would like the message "name is too short" to be displayed if last_name.errors.minlength evaluates to true. However, I encounter an error: Property 'minlength' comes from an index signature, so it must be accessed with ['minlength']. ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

Issue encountered when attempting to save items in the browser's local storage

I'm encountering an issue: ERROR Error: Uncaught (in promise): DataCloneError: Failed to execute 'put' on 'IDBObjectStore': Position object could not be cloned. Error: Failed to execute 'put' on 'IDBObjectStore& ...

Is there a way to identify when a user is returning to a previous page in Angular2

How can I detect if a user has pressed the back button in their browser to navigate back while using Angular? Currently, I am subscribing to router events to achieve this. constructor(private router: Router, private activatedRoute: ActivatedRoute) { ...

Discovering Type Definitions in Nuxt.js Project Without Manual Imports in VSCode: A Step-by-Step Guide

Having issues with VSCode not recognizing type definitions automatically in a Nuxt.js project with TypeScript. I'm looking to avoid manually importing types in every file. Here's my setup and the problem I'm facing: Configuration My tsconfi ...

How can I retrieve the filename from my request block when using multer?

How can I access the file name in my request body and store it in my database? Here's the code I have so far: var storage = multer.diskStorage({ destination: function (req, file, callback) { var name = 'public/images/&apos ...

Angular 7: Separate Views for Search Bar and Results

Two components have been developed: search-bar.component.ts: displayed in all views search.component.ts: responsible for displaying the results (response from a REST API) The functionality is as follows: whenever I need to perform a global search (produ ...

Navigating the Angular Upgrade in the New Year of 2022

After browsing through https://update.angular.io/?v=12.0-13.0, I came across some instructions to update Angular in Visual Studio. npx @angular/cli@13 update @angular/core@13 @angular/cli@13 Everything seemed fine, but I became puzzled by the different ...

Review the file's content prior to uploading

Before uploading a zip or rar file to the server, I need to ensure that the content is safe and not malicious. Let me paint the picture for you. In my web project, there are two types of users: 1: Regular registered users 2: Project administrators Any ...

Creating object types in typescript from object keys: a step-by-step guide

In my JavaScript object, I have two keys named foo and bar. const x = { foo: '', bar: '' } I also have a function called abc that takes a value (which can only be either foo or bar). function abc(value: string) { const selected = x[v ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...