Skip to content

Instantly share code, notes, and snippets.

@Krabaton
Created October 7, 2020 12:18
Show Gist options
  • Save Krabaton/3c0a2dc52795ce323c9391d16523db51 to your computer and use it in GitHub Desktop.
Save Krabaton/3c0a2dc52795ce323c9391d16523db51 to your computer and use it in GitHub Desktop.
Upload Multer
const createError = require('http-errors')
const express = require('express')
const path = require('path')
const fs = require('fs').promises
const app = express()
const multer = require('multer')
const uploadDir = path.join(process.cwd(), 'uploads')
const storeImage = path.join(process.cwd(), 'images')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir)
},
filename: (req, file, cb) => {
cb(null, file.originalname)
},
limits: {
fileSize: 1048576,
},
})
const upload = multer({
storage: storage,
})
app.post('/upload', upload.single('picture'), async (req, res, next) => {
const { description } = req.body
const { path: temporaryName, originalname } = req.file
const fileName = path.join(storeImage, originalname)
try {
await fs.rename(temporaryName, fileName)
} catch (err) {
await fs.unlink(temporaryName)
return next(err)
}
res.json({ description, message: 'Файл успешно загружен', status: 200 })
})
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404))
})
app.use((err, req, res, next) => {
res.status(err.status || 500)
res.json({ message: err.message, status: err.status })
})
const isAccessible = (path) => {
return fs
.access(path)
.then(() => true)
.catch(() => false)
}
const createFolderIsNotExist = async (folder) => {
if (!(await isAccessible(folder))) {
await fs.mkdir(folder)
}
}
const PORT = process.env.PORT || 3000
app.listen(PORT, async () => {
createFolderIsNotExist(uploadDir)
createFolderIsNotExist(storeImage)
console.log(`Server running. Use on port:${PORT}`)
})
{
"name": "upload-multer",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"http-errors": "^1.8.0",
"multer": "^1.4.2"
}
}
@barinio
Copy link

barinio commented Dec 29, 2023

const upload = multer({ storage: storage, })
код вище (22-24 рядки) можна прописати як: const upload = multer({ storage }) ?
чи все ж треба і краще залишити як є?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment