我似乎找不到任何关于如何使用 Mongo、NodeJS 和 Angular 取消文件上传的最新答案。我只遇到过一些关于如何删除文件的教程,但这不是我想要的。我希望能够通过单击前端的按钮来取消文件上传过程。
我使用 Mongoose、Multer 和 GridFSBucket 包将我的文件直接存储到 MongoDB 中。我知道我可以通过在前端取消订阅负责上传的订阅者来停止前端的文件上传过程,但是当我取消订阅时,上传过程会在后端继续进行**(是的,我有双重和三重检查。所有块不断上传,直到文件完全上传。)
这是我的角代码:
ngOnInit(): void {
// Upload the file.
this.sub = this.mediaService.addFile(this.formData).subscribe((event: HttpEvent<any>) => {
console.log(event);
switch (event.type) {
case HttpEventType.Sent:
console.log('Request has been made!');
break;
case HttpEventType.ResponseHeader:
console.log('Response header has been received!');
break;
case HttpEventType.UploadProgress:
// Update the upload progress!
this.progress = Math.round(event.loaded / event.total * 100);
console.log(`Uploading! ${this.progress}%`);
break;
case HttpEventType.Response:
console.log('File successfully uploaded!', event.body);
this.body = 'File successfully uploaded!';
}
},
err => {
this.progress = 0;
this.body = 'Could not upload the file!';
});
}
**CANCEL THE UPLOAD**
cancel() {
// Unsubscribe from the upload method.
this.sub.unsubscribe();
}
这是我的NodeJS (Express) 代码:
...
// Configure a strategy for uploading files.
const multerUpload = multer({
// Set the storage strategy.
storage: storage,
// Set the size limits for uploading a file to 120MB.
limits: 1024 * 1024 * 120,
// Set the file filter.
fileFilter: fileFilter
});
// Add new media to the database.
router.post('/add', [multerUpload.single('file')], async (req, res)=>{
return res.status(200).send();
});
取消上传而不在数据库中留下任何块的正确方法是什么?