【问题标题】:How to abort a file upload in PrimeNG’s FileUpload component?如何在 PrimeNG 的 FileUpload 组件中中止文件上传?
【发布时间】:2019-04-12 14:38:36
【问题描述】:

1。总结

根据 PrimeNG 的 FileUpload component 中选择的文件,我想中止将文件上传到后端服务器以获取特定的文件名模式。 Angular 6.0.7,PrimeNG 6.0.2。

2。第一种方法

2.1。 HTML部分

<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。结果

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

3。第二种方法

3.1 TypeScript 部分

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

3.2 结果

在传输之前删除选定的文件,这会按预期“停止”上传。但是后端服务器抱怨浏览器控制台中的空请求是可以理解的:Failed to load resource: the server responded with a status of 400 ()

4。待解决的挑战

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

【问题讨论】:

  • 我也在寻找这个解决方案...

标签: angular typescript file-upload upload primeng


【解决方案1】:

event.xhr.abort();

用于中止发送的请求。所以它在 onBeforeUpload 甚至 onBeforeSend 内都不起作用。这就是docs 所说的:

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

无论你做什么,它仍然会发出请求,直到你指定 customUpload="true" (docs)

你可以这样解决它:

  1. 指定自定义上传

     <p-fileUpload #fileUpload customUpload = "true" (uploadHandler)="handleUpload($event)">
    
  2. 在你的 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. 以及进行实际调用的功能

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

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 2018-05-22
    • 1970-01-01
    • 2020-06-08
    • 2019-02-16
    • 2017-06-24
    • 2017-06-09
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多