我试图在角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);
});
}组件
<input type="file"
id="file" (change)="handleFileInput($event.target.files)">请建议我如何修改,以使我的功能如所述。
发布于 2021-06-23 12:50:03
对于第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
}
})) https://stackoverflow.com/questions/64369660
复制相似问题