File uploading for routes.
Some schema of "multer" package using
- 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)
-
Extract file from request (from special field) and put it to the
temporary folder
- npm i uuid
-
Create folder for temporary file "temp"
const tempDir = path.join(process.cwd(), 'temp');
- Add multer settings
-
Create middleware with extracting file from special field
"avatar"
const avatarUploadMdw = uploadImageSettings.single('avatar');
- Add POST route for extracting file to temporary folder
- Create request in POSTMAN ( Look at point in POST requests guide Request for file sending )
Code sum up to step 1
See the Pen 93__sumUpCode__fileUploading_with-multer by Andrii (@imitator) on CodePen.
-
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")
- Create "upload" folder
-
Create full CTRL
See the Pen 94__sumUpCode__fileUploading_with-multer_part-1 by Andrii (@imitator) on CodePen.
Example 2. When images adding
to the collection
(add time of adding file for the reason of
avoiding the same name of files)
-
-
Extract file from request (from special field) and put it to
the temporary folder
-
In this example we made first part of settings in the file middlewares\extractFileMDW.js
- Add POST route for extracting file to temporary folder
- Create request in POSTMAN ( Look at point in POST requests guide Request for file sending )
-
-
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.