skip to Main Content

The usual Multer setup saves files right away, as shown in the basic example below:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  // my database-related code... 
});

When implementing this code, the image is still saved to the upload folder if an error occurs during the database entry process. I aim to ensure the image is saved only when the database entry succeeds. How can I achieve this?

2

Answers


  1. Tell me one thing do you have separate schema for storing the images(uploads) ????

    for example like in mongoose you want to store the image path directly in the document object.

    image:somePath or ObjectID(reference)
    

    or have separate schema for storing upload and then links vi FID

    1:Case One

    if you want to store the imgae path directly in the doucment then you have to store the image first let me tell you why??.Because when you’re creating that document and if you have the filed which stores the imagePath and if you haven’t store image then what will you store in that field instaed of image Address ???

    Solution
    what you can you do here is something called

    fs.unlink( path, callback )
    

    this will allow you to delete the file in case some error got occur and document is not created.

    Login or Signup to reply.
  2. You can catch the MulterError by calling the middleware itself inside the request callback as opposed to before it. If the file saves you can save it’s reference to the database. If the database then errors you can delete the file like so:

    const fs = require('fs');
    const multer = require('multer');
    const upload = multer({ dest: 'uploads/' }).single('avatar')
    
    app.post('/profile', (req, res) => {
       upload(req, res, async (err) => {
          if (err instanceof multer.MulterError) {
             // Don't save to database
             console.log(err);
             return res.send({message: 'Error while uploading'})
          } else if (err) {
             // Different kind of error
             console.log(err);
             return res.send({message: 'Error on server'})
          } else {
             try {
                // All went well so can save to database
                const upload = await UploadModel.create({key: 'value'})
                return res.send({message: 'File saved'})
             } catch(e) {
                console.log(e);
                // Something wet wrong with the database
                // Need to delete the file
                fs.unlink('path/to/file.jpg', (err) => {
                   if (err) throw err;
                   console.log('File was deleted');
                });
                return res.send({message: 'File not saved'})   
             }
          }
       })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search