-
-
Save theStrangeAdventurer/9e5e98a354fa71ecc64b19ad0634a4ea to your computer and use it in GitHub Desktop.
multer and gm - upload and save multiple images with varios resolutions (nodejs, express)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multer from 'multer' | |
import passportManager from '../../config/passport' | |
import fs from 'fs' | |
import gm from 'gm' | |
import mime from 'mime' | |
import 'array-foreach-async' | |
const storage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
const { params: { folder, subfolder } } = req | |
if (!fs.existsSync(`${__dirname}/../../public/images/${folder}`)) { | |
fs.mkdirSync(`${__dirname}/../../public/images/${folder}`); | |
} | |
if (!fs.existsSync(`${__dirname}/../../public/images/${folder}/${subfolder}`)) { | |
fs.mkdirSync(`${__dirname}/../../public/images/${folder}/${subfolder}`); | |
} | |
cb(null, `${__dirname}/../../public/images/${folder}/${subfolder}`) | |
}, | |
filename: function (req, file, cb) { | |
const { params: { filename } } = req | |
cb(null, filename) | |
} | |
}) | |
const upload = multer({ storage: storage }) | |
const resizeImage = (width, height, path, outPath) => new Promise((resolve, reject) => { | |
gm(path) | |
.resize(width, height, '^') | |
.gravity('Center') | |
.extent(width, height) | |
.noProfile() | |
.write(outPath, function (err) { | |
if (err) { | |
reject(err) | |
} | |
resolve({ | |
result: true | |
}) | |
}) | |
}) | |
export default app => { // app is express | |
app.route('/upload/single/:folder/:subfolder/:filename') | |
.post(upload.single('image'), function (req, res) { | |
const { params: { filename }, file } = req | |
const ext = mime.getExtension(file.mimetype) | |
const save = file.destination | |
let savedImgs = [] | |
const sizes = [ | |
{ | |
width: 300, | |
height: 250, | |
prefix: `-300-250px` | |
}, | |
{ | |
width: 336, | |
height: 280, | |
prefix: `-336-280px` | |
}, | |
{ | |
width: 800, | |
height: 600, | |
prefix: `-800-600px` | |
}, | |
] | |
if (!fs.existsSync(save)) { | |
fs.mkdirSync(save); | |
} | |
sizes.forEachAsync(async ({ width, height, prefix }, i) => { | |
await resizeImage(width, height, file.path, `${save}/${filename}${prefix}.${ext}`) | |
const relPath = `${save}/${filename}${prefix}.${ext}`.split('/images/').pop() | |
savedImgs.push({ | |
src: relPath, | |
width, | |
height | |
}) | |
if (i === (sizes.length - 1)) { | |
fs.unlink(file.path, function (err) { | |
if (err) | |
throw err | |
return res.status(200).send({ result: true, savedImgs }) | |
}) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First you must install gm on your OS, for example in ubuntu