Multer deletes uploaded image, if new uploaded image hits a limit (File to large, etc)

Viewed 72

I am writing an api in node.js and I'm using multer for image uploading. I want to upload a cover to a book, which works fine. If I upload a new cover to the same book and the image is within the limits (filesize < 1 MB), then the old cover will be overwritten with the new one, which is what I want but if already a cover is present and I upload a new cover that is not within the limits (filesize > 1 MB), then the old (present) cover will be deleted! And that is not the behavior I want. If the uploaded image is too large I don't want the old (present) cover to be deleted.

For some clarification: I upload the image to the filesystem and only store the link to the image in the database.

Successful upload:

Json Response

cover.jpeg is saved to filesystem

File too large upload (to the same book):

Json Response

Present cover.jpeg is deleted!

Multer code:

const book_cover_upload = multer({
  storage: multer.diskStorage({
     destination: book_uploads_destination,
     filename: cover_filename
}),
  limits: {
    fileSize: 1000000 // 1 Megabyte
},
  fileFilter: book_file_filter 
})

book_uploads_destination function:

const book_uploads_destination = (req, file, cb) => {
  const destination = path.join('user_uploads', req.user._id.toString(), 'books', req.params.id.toString())

  if (!fs.existsSync(destination))
     fs.mkdirSync(destination, { recursive: true })

  cb(null, destination)
}

cover_filename function:

const cover_filename = (req, file, cb) => {
  const splited_mime_type = file.mimetype.split('/')
  const extension = splited_mime_type[splited_mime_type.length - 1]

  cb(null, 'cover.' + extension)
}

book_file_filter function:

const book_file_filter = async (req, file, cb) => {
  const book = await Book.findOne({ _id: req.params.id, entry_created_by: req.user._id })

  if (!book)
      return cb(new Error('No book found with given id!'))

  req.book = book

  if (file.mimetype !== "image/jpeg" && file.mimetype !== "image/png")
      return cb(new Error('Image must be in JPEG/JPG or PNG format!'))

  cb(undefined, true)
}

I've made some tests. If I change the cover filename in the cover_filename function from 'cover.' + extension to 'cover_something.' + extension and then upload an image which is too large, the present cover image (cover.jpeg, which I uploaded before) will NOT be deleted!

So I think multer always uploads the image and overwrittes the old (present) image (which I uploaded before) and THEN it checks if the file is too large and deletes the just overwritten image, if it is too large.

Can I somehow change that behavior, so it don't overwrittes and deletes the old image, if it hits the limits (file too large)?

Thanks!

0 Answers
Related