- Популярные видео
- Авто
- Видео-блоги
- ДТП, аварии
- Для маленьких
- Еда, напитки
- Животные
- Закон и право
- Знаменитости
- Игры
- Искусство
- Комедии
- Красота, мода
- Кулинария, рецепты
- Люди
- Мото
- Музыка
- Мультфильмы
- Наука, технологии
- Новости
- Образование
- Политика
- Праздники
- Приколы
- Природа
- Происшествия
- Путешествия
- Развлечения
- Ржач
- Семья
- Сериалы
- Спорт
- Стиль жизни
- ТВ передачи
- Танцы
- Технологии
- Товары
- Ужасы
- Фильмы
- Шоу-бизнес
- Юмор
How to upload multiple Photos with multer and node modules?
(a cautionary note, YouTube doesn't allow the greater than symbol in the description so I'm forced to use a unicode lookalike ⋗, please replace it if you copy and paste code from here)
1. At this point we will start adding the ability to upload files from a client request to our server using multer, for that we will add the highlighted code to our REST API:
import express, {json, urlencoded} from 'express'
import morgan from 'morgan'
import morganBody from 'morgan-body'
import multer from 'multer'
// Multer
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
let extension = file.mimetype.split('/')[1]
if (extension === 'x-javascript') extension = 'js'
if (extension === 'video/quicktime') extension = 'mov'
if (extension === 'video/x-msvideo') extension = 'avi'
console.log('mimetype: ', file.mimetype, 'extension is: ', extension)
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + '.' + extension)
}
})
const upload = multer({ storage: storage })
const app=express()
app.use((req, res, next)=⋗ {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Connection, User-Agent")
console.log('CORS handler headers sent')
if (req.method === 'OPTIONS') {
console.log('OPTIONS request received, allowing put, post, get');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET')
return res.status(200).json({
'Access-Control-Allow-Methods': 'PUT, POST, GET'
})
}
next() // next means that we go to the next app.use or route
})
app.use(json({ limit: '50mb'}))
morganBody(app)
app.use(morgan('combined'))
const upload_files = (req, res) =⋗ {
// this function will handle the actions that follow the uploading of the files by multer
}
/****************************************************************/
/* HERE WE SET UP A ROUTE THAT WILL LISTEN TO POST REQUESTS IN */
/* THE /upload_files ROUTE */
app.post('/upload_files', upload.array('files', 12), upload_files) // 'files' must be the 'name' of the input field in the html form of the client that requests the upload
app.listen(process.env.Node_PORT, ()=⋗{
console.log('listening to Port: ', process.env.Node_PORT)
})
2. The line import multer from 'multer' imports into the module the multer package. The group of lines that starts with const storage = multer.diskStorage({ fills the storage object with the parameters we need. Each time a files is stored (we are illustrating the multiple files case since it is the most generic one). Multer automatically provides a callback (cb) with the file object for both the destination and the name of the file that will be used. Please note that the directory to receive the files must exist in the server for this case. For the destination path we are using the same path for all files and for the name we are changing the name to a randomly created name. We are also using the mimetype of the file to extract its extension. The function split cuts the string into an array, of two strings separated by the '/' symbol – in this case- and the [1] picks the second element of the array. The if statements assing the extension to the mimetypes that don't spell it out specifically. The line const upload = multer({ storage: storage }) incorporates the storage model defined before into the upload object in multer. The group const upload_files = (req, res) =⋗ {...} is the function that we will call after multer has finished saving the files. The line app.post('/upload_files', upload.array('files', 12), upload_files) is the actual routing for the POST request that comes in the upload_files/ route, the first value is the route itself 'upload_files', the second value calls the multer middleware upload.array('files', 12), where files is the identifier that the client used to identify the files array it sent to the server. 12 is the maximum number of files that will be processed. This is followed by a middleware (upload_files()), that we add to perform some post processing of the received files.
10. Video for how to handle __dirname is not defined inside the ES module scope: https://youtu.be/kn9qhxpFW6c
12. How to read the body of a post request in node: https://youtu.be/0JlSfiN1Yj0 (this video)
13. How to pass secrets in node using dotenv: https://youtu.be/kn9qhxpFW6c
14. CORS essentials: https://youtu.be/9A4nGqZep1U
15. Monitoring in the console requests, responses and their body with Morgan: https://youtu.be/2hTu3w94T0k
16. Multer and how to upload multiple files/pictures/photos to a node module server is described in video: https://youtu.be/Ee2faNRDFEs
17. Three settings you must change in VSC: https://youtu.be/ujPkkASxims
Видео How to upload multiple Photos with multer and node modules? канала Julio Spinelli
1. At this point we will start adding the ability to upload files from a client request to our server using multer, for that we will add the highlighted code to our REST API:
import express, {json, urlencoded} from 'express'
import morgan from 'morgan'
import morganBody from 'morgan-body'
import multer from 'multer'
// Multer
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
let extension = file.mimetype.split('/')[1]
if (extension === 'x-javascript') extension = 'js'
if (extension === 'video/quicktime') extension = 'mov'
if (extension === 'video/x-msvideo') extension = 'avi'
console.log('mimetype: ', file.mimetype, 'extension is: ', extension)
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + '.' + extension)
}
})
const upload = multer({ storage: storage })
const app=express()
app.use((req, res, next)=⋗ {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Connection, User-Agent")
console.log('CORS handler headers sent')
if (req.method === 'OPTIONS') {
console.log('OPTIONS request received, allowing put, post, get');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET')
return res.status(200).json({
'Access-Control-Allow-Methods': 'PUT, POST, GET'
})
}
next() // next means that we go to the next app.use or route
})
app.use(json({ limit: '50mb'}))
morganBody(app)
app.use(morgan('combined'))
const upload_files = (req, res) =⋗ {
// this function will handle the actions that follow the uploading of the files by multer
}
/****************************************************************/
/* HERE WE SET UP A ROUTE THAT WILL LISTEN TO POST REQUESTS IN */
/* THE /upload_files ROUTE */
app.post('/upload_files', upload.array('files', 12), upload_files) // 'files' must be the 'name' of the input field in the html form of the client that requests the upload
app.listen(process.env.Node_PORT, ()=⋗{
console.log('listening to Port: ', process.env.Node_PORT)
})
2. The line import multer from 'multer' imports into the module the multer package. The group of lines that starts with const storage = multer.diskStorage({ fills the storage object with the parameters we need. Each time a files is stored (we are illustrating the multiple files case since it is the most generic one). Multer automatically provides a callback (cb) with the file object for both the destination and the name of the file that will be used. Please note that the directory to receive the files must exist in the server for this case. For the destination path we are using the same path for all files and for the name we are changing the name to a randomly created name. We are also using the mimetype of the file to extract its extension. The function split cuts the string into an array, of two strings separated by the '/' symbol – in this case- and the [1] picks the second element of the array. The if statements assing the extension to the mimetypes that don't spell it out specifically. The line const upload = multer({ storage: storage }) incorporates the storage model defined before into the upload object in multer. The group const upload_files = (req, res) =⋗ {...} is the function that we will call after multer has finished saving the files. The line app.post('/upload_files', upload.array('files', 12), upload_files) is the actual routing for the POST request that comes in the upload_files/ route, the first value is the route itself 'upload_files', the second value calls the multer middleware upload.array('files', 12), where files is the identifier that the client used to identify the files array it sent to the server. 12 is the maximum number of files that will be processed. This is followed by a middleware (upload_files()), that we add to perform some post processing of the received files.
10. Video for how to handle __dirname is not defined inside the ES module scope: https://youtu.be/kn9qhxpFW6c
12. How to read the body of a post request in node: https://youtu.be/0JlSfiN1Yj0 (this video)
13. How to pass secrets in node using dotenv: https://youtu.be/kn9qhxpFW6c
14. CORS essentials: https://youtu.be/9A4nGqZep1U
15. Monitoring in the console requests, responses and their body with Morgan: https://youtu.be/2hTu3w94T0k
16. Multer and how to upload multiple files/pictures/photos to a node module server is described in video: https://youtu.be/Ee2faNRDFEs
17. Three settings you must change in VSC: https://youtu.be/ujPkkASxims
Видео How to upload multiple Photos with multer and node modules? канала Julio Spinelli
Комментарии отсутствуют
Информация о видео
17 декабря 2021 г. 6:03:28
00:16:00
Другие видео канала




















