组件中中止文件上传

组件中中止文件上传

本文介绍了如何在 PrimeNG 的 FileUpload 组件中中止文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于在 PrimeNG 的 FileUpload 组件中选择的文件,我想中止文件上传到后端服务器以获得特定的文件名模式.Angular 6.0.7,PrimeNG 6.0.2.

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.

<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.打字稿部分

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

2.3.结果

该方法被调用没有任何错误,但上传没有被取消.

2.3. Result

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

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

3.2 结果

所选文件在传输前被删除,这会按预期停止"上传.但是后端服务器抱怨浏览器控制台中的空请求是可以理解的:加载资源失败:服务器响应状态为 400().

如何在选择特定文件后中止 PrimeNG FileUpload 组件中的文件上传?

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

推荐答案

event.xhr.abort();

event.xhr.abort();

用于中止发送的请求.所以它不会在 onBeforeUpload 甚至 onBeforeSend 中工作.这就是 docs 所说的:

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

如果请求已经发送,则 XMLHttpRequest.abort() 方法会中止请求.

无论您做什么,它仍会发出请求,直到您指定 customUpload="true";(文档)

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

这就是你可以解决的方法:

That's how you can solve it:

  1. 指定自定义上传

  1. Specify custom upload

 <p-fileUpload #fileUpload customUpload = "true" (uploadHandler)="handleUpload($event)">

  • 在你的 component.ts 中处理它

  • 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.
         }
       });
     }}
    

  • 和函数进行实际调用

  • 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);
     }
     

  • 这篇关于如何在 PrimeNG 的 FileUpload 组件中中止文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-24 04:16