【问题标题】:Upload zip files in angular 8以角度 8 上传 zip 文件
【发布时间】:2021-01-29 19:47:54
【问题描述】:

我正在尝试在 Angular 8 应用程序中实现 zip 文件上传功能。我需要满足的三个条件是:

1. Only allow zip files to be uploaded else throw error message
2. File size should not cross 3 MBs else throw error message
3. When I choose zip file, it should show progress bar but file should only be uploaded via REST API call when I click 'Register' button separately.

目前我实现的是:文件上传服务

postFile(fileToUpload: File, header): Observable<any> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    if (fileToUpload.size <= 3048576)
    return this.httpClient.post(endpoint, formData, { headers: header })
      .pipe(map(data => {
        console.log(data);
        return data;
      },error => {
        console.log(error, 'reduce file size');
      })) 
    }

组件 TS 文件

handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
  this.fileUploadService.postFile(this.fileToUpload, this.headers).subscribe(data => {
    // do something, if upload success
    console.log('the file has been uploaded successfully', data);
    }, error => {
      console.log(error);
    });
}

组件 HTML

<input type="file"
 id="file" (change)="handleFileInput($event.target.files)">

请建议我如何修改才能使我的功能与描述的一样。

【问题讨论】:

    标签: html angular typescript file-upload angular8


    【解决方案1】:

    对于第 1 点和第 2 点,您应该在代码中添加一个验证函数来检查文件扩展名和大小。 只有文件通过验证才能上传。 除此之外,您可能应该在验证失败时向用户返回某种反馈。

    您可以跟踪文件上传进度(并显示进度条)向 .post 方法添加其他选项并监听特定事件

    return this.httpClient.post(endpoint, formData, { 
     headers: header,
     reportProgress: true, 
     observe: 'events'
    }).pipe(map(event => {  
     if (event.type === HttpEventType.Response) {
      // upload complete
     }
     if (event.type === HttpEventType.UploadProgress) {    
      // the event contains information about loaded data
      // you can use event.loaded and event.total to display the progress bar
     }
    })) 
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2021-11-27
      • 2021-07-02
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多