如何为Angular到NestJS的文件上传添加进度条?
实现Angular到NestJS文件上传的进度显示
我已经搭建好通过Angular向NestJS上传文件的系统,但无法查看上传进度,不清楚何时完成,这十分困扰。请问有实现上传进度显示的方法吗?以下是我的前后端代码:
前端(Angular)代码
let formData = new FormData() let dateX = cur_day + hours + minutes + seconds; // 变量已省略 formData.append("dest", `${this.chatid}/${this.userData.userid}/${dateX}/`) this.draftImages.forEach((fileData: any) => { formData.append("file", fileData.file, fileData.name) console.log(fileData.file); }) console.log(formData) this.http.post<any>("http://localhost:3000/chat/message/dm/uploadImg", formData).subscribe((result) => { console.log(result, formData) let filesUploaded: any = [] this.draftImages = [] Array.from(result).forEach((file: any) => { filesUploaded.push(file.destination + file.originalname) }) this.dmService.sendMessage({ message: message, chatid: this.chatid, userid: this.userData.userid, username: this.userData.username, pfp: this.userData.pfp, files: filesUploaded }); })
后端(NestJS)代码
@Post("uploadImg") @UseInterceptors( AnyFilesInterceptor({ storage: diskStorage({ destination: function (req: any, file, cb) { console.log(file); function mkdirRecursiveSync(path: string) { if (!existsSync(path)) { mkdirRecursiveSync(dirname(path)); mkdirSync(path); } } const destPath = `CDN/attachments/${req.body.dest}`; mkdirRecursiveSync(destPath); console.log(req.body) cb(null, destPath); }, filename: function (req, file, cb) { console.log(file) cb(null, file.originalname); }, }), }) ) async uploadedFile(@UploadedFiles() file) { console.log(file) return file; }
实现上传进度显示的方法
前端修改(Angular)
要获取上传进度,需在HTTP请求中开启进度报告选项,并监听完整的HTTP事件流:
- 修改请求配置并监听事件:
// 先导入HttpEventType import { HttpClient, HttpEventType } from '@angular/common/http'; // 替换原有的post请求代码 this.http.post<any>( "http://localhost:3000/chat/message/dm/uploadImg", formData, { reportProgress: true, // 开启进度报告 observe: 'events' // 监听所有HTTP事件 } ).subscribe({ next: (event) => { // 处理上传进度事件 if (event.type === HttpEventType.UploadProgress) { const percentDone = Math.round(100 * event.loaded / (event.total || 1)); console.log(`上传进度:${percentDone}%`); // 可将进度值绑定到UI组件,比如进度条 // this.uploadProgress = percentDone; } // 处理上传完成事件 else if (event.type === HttpEventType.Response) { const result = event.body; console.log(result, formData); let filesUploaded: any = []; this.draftImages = []; Array.from(result).forEach((file: any) => { filesUploaded.push(file.destination + file.originalname); }); this.dmService.sendMessage({ message: message, chatid: this.chatid, userid: this.userData.userid, username: this.userData.username, pfp: this.userData.pfp, files: filesUploaded }); } }, error: (err) => { console.error("上传失败", err); } });
后端注意事项(NestJS)
你的现有后端代码无需修改,但需确保:
AnyFilesInterceptor会在所有文件上传完成后才返回响应,不要在中间过程提前发送响应- 目录创建逻辑(
mkdirRecursiveSync)是同步执行的,不会打断文件上传的进度计算
内容的提问来源于stack exchange,提问作者Almaszosz
相关产品推荐
相关产品推荐

