How to abort a file upload in PrimeNG’s FileUpload component?

Viewed 1160

1. Summary

Based on the selected file in PrimeNG's FileUpload component, I want to abort the file upload to the backend server for specific filename patterns. Angular 6.0.7, PrimeNG 6.0.2.

2. First approach

2.1. HTML part

<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 part

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

2.3. Result

The method was called without any errors, but the upload was not canceled.

3. Second approach

3.1 TypeScript part

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

The selected files are removed before transfer, which "stops" the upload as intended. But the backend server understandably complains about the empty request in the browser console: Failed to load resource: the server responded with a status of 400 ().

4. To be solved challenge

How can I abort the file upload in PrimeNG FileUpload component after selection of specific files?

1 Answers

event.xhr.abort();

is for aborting the sent request. So it won't work inside onBeforeUpload or even onBeforeSend. That's what docs say:

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

Whatever you do, it will still make a request until you specify customUpload="true" (docs)

That's how you can solve it:

  1. Specify custom upload

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

     handleUpload(event: any) {
    
     // Do whatever you want here
    
     if(condition) {
       // Good to go!
       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
           // Your code: display a message, update list of files, etc.
         }
       });
     }}
    
  3. And function to make an actual call

    sendFile(formData) {
         // http is HttpClient. You can override it and add required authentication headers, etc.
         return this.http.post(this.HierarchyFileUploadUrl, formData);
     }
     
Related