gancio/server/api/storage.js

50 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-04-03 00:25:12 +02:00
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const mkdirp = require('mkdirp')
const sharp = require('sharp')
2021-03-05 14:17:10 +01:00
const log = require('../log')
2021-09-27 10:42:17 +02:00
const config = require('../config')
2019-04-03 00:25:12 +02:00
2019-07-03 16:58:24 +02:00
try {
mkdirp.sync(config.upload_path + '/thumb')
2021-07-08 20:41:56 +02:00
} catch (e) {}
2019-04-03 00:25:12 +02:00
const DiskStorage = {
2019-09-11 19:12:24 +02:00
_handleFile (req, file, cb) {
2022-04-27 12:34:58 +02:00
const filename = crypto.randomBytes(16).toString('hex')
const sharpStream = sharp({ failOnError: true })
const promises = [
2022-05-06 23:03:26 +02:00
sharpStream.clone().resize(500, null, { withoutEnlargement: true }).jpeg({ mozjpeg: true, progressive: true }).toFile(path.resolve(config.upload_path, 'thumb', filename + '.jpg')),
sharpStream.clone().resize(1200, null, { withoutEnlargement: true } ).jpeg({ quality: 95, mozjpeg: true, progressive: true }).toFile(path.resolve(config.upload_path, filename + '.jpg')),
2022-04-27 12:34:58 +02:00
]
2019-04-03 00:25:12 +02:00
2022-04-27 12:34:58 +02:00
file.stream.pipe(sharpStream)
Promise.all(promises)
.then(res => {
2022-05-03 12:08:10 +02:00
const info = res[1]
2022-04-27 12:34:58 +02:00
cb(null, {
destination: config.upload_path,
filename: filename + '.jpg',
path: path.resolve(config.upload_path, filename + '.jpg'),
height: info.height,
width: info.width,
size: info.size,
})
})
.catch(err => {
console.error(err)
req.err = err
cb(null)
2019-04-03 00:25:12 +02:00
})
},
2022-04-27 12:34:58 +02:00
_removeFile (_req, file, cb) {
delete file.destination
delete file.filename
fs.unlink(file.path, cb)
delete file.path
}
2019-04-03 00:25:12 +02:00
}
module.exports = DiskStorage