如果取消上传,则不会删除Multer文件

问题描述

Multer 中是否有任何功能,如果请求被取消,则可以从服务器中删除文件的上载部分

解决方法

很长一段时间以来,这一直是问题的根源。在github:https://github.com/expressjs/multer/issues/259上看到此问题,对话中列出了各种解决方法。

在我们的项目中,我们当前使用的叉子是“ kyleerik / multer#kyleerik-patch-1”,它被提到in this comment,并且到目前为止效果很好。

,

这是我的方法对我有用


filename: (req,file,cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const fileName =
      file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname);
    cb(null,fileName);    
    req.on('aborted',() => {
      const fullFilePath = path.join('uploads','videos',fileName);
      file.stream.on('end',() => {
        fs.unlink(fullFilePath,(err) => {
          console.log(fullFilePath);
          if (err) {
            throw err;
          }
        });
      });
      file.stream.emit('end');
    })
  }