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

Is there a way to clear the selected date in a date picker while using MatDateRangeSelectionStrategy?

Recently, I was experimenting with the date picker feature of Angular Material and stumbled upon this particular example After implementing this example with my own logic, everything seemed to be working perfectly fine except for one issue. The dates were ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Eliminating Angular's @Injectable decorator in npm build process

I have encountered a setback while working on a small helper package for Angular. The issue I am facing is related to an exported class that serves as an Angular service and is decorated with @Injectable(). After running npm run build, the compiled class ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

Issue with displaying children in Angular 2 router: children components not appearing on the

I am currently in the process of incorporating a user authentication bundle into my Angular 2 project by following this tutorial at . I have organized all the files from the bundle into a parent folder named "loginMGR", and modified the module, components ...

I haven't encountered any type warnings in the places where I anticipated them

When I define an object like this: const x: { str: string, num: number } = { str: str, num: not_a_num }; I am surprised to find that even though 'not_a_num' is a string and not a number, the compiler does not throw an error. Instead, ...

Formulate a multi-line string using a collection in React's JavaScript framework

I'm working on a React function that involves a set and I need to update an HTML element using the data from this set. Below is an example of my code: const updateElement = (mySet) => { document.getElementById('myId').innerHTML = Arra ...

Determine whether the ng bootstrap modal has already been opened

Is there a way to determine if a modal window is open? In order to accomplish this, I create a variable called modalInstance: NgbModalRef; and initialize the modal by using the code below this.modalInstance = this.modalService.open(UpdateModalConten ...

Error encountered: An unexpected name token (DocumentAttributes) was found while using webpack and UglifyJs

Currently, I am working on generating word documents with images using the angular typescript code and docx 5.0.2 version. However, when utilizing webpack.optimize.UglifyJsPlugin, I encountered the following error during the code build process: Unexpected ...

Is there a way to access the actionsObserver value from the Angular state?

When attempting to view state data using the code line this.store.select(selectUser), I am able to see the data as expected under actionsObserve. However, I am facing difficulty reading the data in actionsObserve with this line: this.store.select(selectUs ...

Design a TypeScript interface inspired by a set static array

I am working with an array of predefined strings and I need to create an interface based on them. To illustrate, here is an example of pseudo-interfaces: const options = ["option1", "option2", "option3"]; interface Selection { choice: keyof options; ...

Encountering Issue: Unable to locate control with the given name in Angular when generating Dynamic Form with FormGroup

As a beginner in Angular, I aim to develop a dynamic Survey Form that can adjust its questions and input types based on the area. These changes are fetched as JSON data through API calls. Here is the relevant code snippet: .ts File export class Maintenan ...

Receiving an error when attempting to inject the Router in a component constructor without using the elvis operator

Upon launching my app, I desire the route /home to be automatically displayed. Unfortunately, the Angular 2 version I am utilizing does not support the "useAsDefault: true" property in route definitions. To address this issue, I considered implementing th ...

Exploring simultaneous image uploads with Codeigniter and HTML5

Example View <?=form_open_multipart('upload/process');?> <input type="file" multiple="multiple" name="userfile[]" id="userfile" /> <?=form_submit('upload', 'Upload');?> <?=form_close() ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

Hiding the line connector between data points in ChartJs

I recently took over a project that includes a line chart created using Chart.js by the previous developer. My client has requested that I do not display a line between the last two data points. Is this possible with Chart.js? I have looked through the doc ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...

Encountering challenges while integrating Angular with a Laravel forum creation project

Currently, I am working on building a forum application that involves users, posts, and comments using Laravel. However, the next step in my project requires integrating Angular, which is new territory for me and I'm not sure where to start. I have a ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...