Vaibhav Jain
Vaibhav Jain

Reputation: 39

Multer file is not removed if upload is canceled

Is there Any Function in Multer To Remove uploaded part of the File from the server if The Request gets Cancelled

Upvotes: 3

Views: 452

Answers (2)

Vaibhav Jain
Vaibhav Jain

Reputation: 39

Here is my approach worked for me


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');
    })
  }

Upvotes: 0

eol
eol

Reputation: 24565

This has been a bug in multer for a very long time. See this issue on github: https://github.com/expressjs/multer/issues/259, where various workarounds are listed in the conversation.

In our project we're currently using the fork "kyleerik/multer#kyleerik-patch-1" which is mentioned in this comment and it has been working fine so far.

Upvotes: 3

Related Questions