Home > Software engineering >  Node/express - cancel multer photo upload if other fields validation fails
Node/express - cancel multer photo upload if other fields validation fails

Time:02-04

I have multer as middleware before editing user function. The thing is that multer uploads photo no matter what, so I am wondering if there is a way to somehow cancel upload if e.g. email is invalid. I tried to delete uploaded image through function via fs.unlink if there is validation error within edit function, but I get "EBUSY: resource busy or locked, unlink" error. I guess that multer uploads at the same time while I try to delete image. Any ideas how to solve this?

CodePudding user response:

on your function make a try/catch block and handle on error throw

import { unlink } from 'node:fs/promises';
import path from 'path'

// code ...

// inside your function

const img  = req.file // this needs to be outside the try block

try {

     // your code, throw on failed validation

} catch (e) {
   if (img) {
        // depends on where you store in multer middleware
        const img_path = path.resolve(YOUR_PATH, img.filename) 
        await unlink(img_path);

        console.log(`deleted uploaded ${ img_path }`);
    }

    // revert transaction or anything else
}

CodePudding user response:

Nowadays, applications usually separates uploading file API from data manipulating API for some features like previewing/editing image. Later, they can run a background job to clean unused data.

But if it's necessary in your case, we can use multer's builtin MemoryStorage to keep file data in memory first, then save it to disk after validation completes.

const express = require('express');
const app = express();

const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage });
const fs = require('fs');

app.post("/create_user_with_image", upload.single('img'), (req, res) => {
  // Validation here

  fs.writeFile(`uploads/${req.file.originalname}`, req.file.buffer, () => {
    res.send('ok');
  });
});

Note: as multer documentation said, this solution can cause your application to run out of memory when uploading very large files, or relatively small files in large numbers very quickly.

  • Related