【发布时间】:2021-02-25 16:58:05
【问题描述】:
我似乎找不到任何关于如何使用 Mongo、NodeJS 和 Angular 取消文件上传的最新答案。我只遇到过一些关于如何删除文件的教程,但这不是我正在寻找的。我希望能够通过单击前端的按钮来取消文件上传过程。
我使用 Mongoose、Multer 和 GridFSBucket 包将我的文件直接存储到 MongoDB 中。我知道我可以通过取消订阅前端负责上传的订阅者来停止前端的文件上传过程,但是当我上传时,上传过程会继续在后端进行取消订阅**(是的,我已经检查了两次和三次。在文件完全上传之前,所有块都会不断上传。)
这是我的 Angular 代码:
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();
});
什么是取消上传而不在数据库中留下任何块的正确方法?
【问题讨论】:
标签: node.js angular file-upload multer multer-gridfs-storage