File uploading for routes.

Some schema of "multer" package using

Before a start learning uploading files make some points:
  • Create folder for project
  • npm init -y
  • npm i express cors multer
  • npm i nodemon -D
  • Add "start:dev": "nodemon app.js" script --- to package.json
  • Create .prettierrc.json
  • Take simplest backend

    See the Pen 90__simplestBE by Andrii (@imitator) on CodePen.

Example 1. When one image
may be changed by another
(f.e. for avatar)

  1. Extract file from request (from special field) and put it to the temporary folder

    Code sum up to step 1

    See the Pen 93__sumUpCode__fileUploading_with-multer by Andrii (@imitator) on CodePen.

  2. Move file from temporary directory to the "upload" or unlink it (delete file from "temp" in case if file could not be moved to "upload")

Example 2. When images adding
to the collection
(add time of adding file for the reason of
avoiding the same name of files)

  1. Create separate CTRL in controllers\images-collection\addImage.js

    See the Pen 102_addImageCTRL_with-adding-date-to-file by Andrii (@imitator) on CodePen.

    And use it in app.js

    See the Pen 103__app.js__with-using-of-addImageCTRL by Andrii (@imitator) on CodePen.