Skip to content

Instantly share code, notes, and snippets.

@theStrangeAdventurer
Created March 13, 2019 17:19
Show Gist options
  • Save theStrangeAdventurer/9e5e98a354fa71ecc64b19ad0634a4ea to your computer and use it in GitHub Desktop.
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)
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 })
})
}
})
})
}
@theStrangeAdventurer
Copy link
Author

First you must install gm on your OS, for example in ubuntu

sudo add-apt-repository ppa:dhor/myway
sudo apt-get update
sudo apt-get install graphicsmagick

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