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
|
|
|
|
2019-06-11 17:44:11 +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 = [
|
|
|
|
sharpStream.clone().resize(500, null, { withoutEnlargement: true }).jpeg({ quality: 90, mozjpeg: true }).toFile(path.resolve(config.upload_path, 'thumb', filename + '.jpg')),
|
|
|
|
sharpStream.clone().resize(500).webp({ quality: 90, alphaQuality: 0, effort: 6 }).toFile(path.resolve(config.upload_path, 'thumb', filename + '.webp')),
|
|
|
|
sharpStream.clone().resize(1200, null, { withoutEnlargement: true } ).jpeg({ quality: 98, mozjpeg: true }).toFile(path.resolve(config.upload_path, filename + '.jpg')),
|
|
|
|
sharpStream.clone().resize(1200).webp({ quality: 98, alphaQuality: 0, effor: 6 }).toFile(path.resolve(config.upload_path, filename + '.webp')),
|
|
|
|
sharpStream.clone()
|
|
|
|
.resize(6)
|
|
|
|
.png({ quality: 20, palette: true, alphaQuality: 0, effort: 6})
|
|
|
|
.toBuffer()
|
|
|
|
.then(buffer => buffer.toString('base64'))
|
|
|
|
]
|
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 => {
|
|
|
|
const info = res[2]
|
|
|
|
const preview = res[4]
|
|
|
|
console.error(preview)
|
|
|
|
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,
|
|
|
|
preview
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
console.error(err)
|
|
|
|
req.err = err
|
|
|
|
cb(null)
|
2019-04-03 00:25:12 +02:00
|
|
|
})
|
2019-06-11 17:44:11 +02:00
|
|
|
},
|
2022-04-27 12:34:58 +02:00
|
|
|
_removeFile (_req, file, cb) {
|
2019-06-11 17:44:11 +02:00
|
|
|
delete file.destination
|
|
|
|
delete file.filename
|
2020-01-15 23:52:28 +01:00
|
|
|
fs.unlink(file.path, cb)
|
2019-06-11 17:44:11 +02:00
|
|
|
delete file.path
|
|
|
|
}
|
2019-04-03 00:25:12 +02:00
|
|
|
}
|
|
|
|
|
2019-06-11 17:44:11 +02:00
|
|
|
module.exports = DiskStorage
|