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) {
|
2020-07-08 23:02:08 +02:00
|
|
|
const filename = crypto.randomBytes(16).toString('hex') + '.jpg'
|
2019-06-11 17:44:11 +02:00
|
|
|
const finalPath = path.resolve(config.upload_path, filename)
|
|
|
|
const thumbPath = path.resolve(config.upload_path, 'thumb', filename)
|
2019-04-03 00:25:12 +02:00
|
|
|
const outStream = fs.createWriteStream(finalPath)
|
|
|
|
const thumbStream = fs.createWriteStream(thumbPath)
|
|
|
|
|
2021-03-11 12:28:50 +01:00
|
|
|
const resizer = sharp().resize(1200).jpeg({ quality: 98 })
|
2022-01-24 14:12:59 +01:00
|
|
|
const thumbnailer = sharp().resize(500).jpeg({ quality: 98 })
|
2020-01-15 23:52:28 +01:00
|
|
|
let onError = false
|
|
|
|
const err = e => {
|
|
|
|
if (onError) {
|
2021-07-08 20:41:56 +02:00
|
|
|
log.error('[UPLOAD]', err)
|
2020-01-15 23:52:28 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
onError = true
|
2021-07-08 20:41:56 +02:00
|
|
|
log.error('[UPLOAD]', e)
|
2020-01-15 23:52:28 +01:00
|
|
|
req.err = e
|
|
|
|
cb(null)
|
|
|
|
}
|
|
|
|
|
|
|
|
file.stream
|
|
|
|
.pipe(thumbnailer)
|
|
|
|
.on('error', err)
|
|
|
|
.pipe(thumbStream)
|
|
|
|
.on('error', err)
|
|
|
|
|
|
|
|
file.stream
|
|
|
|
.pipe(resizer)
|
|
|
|
.on('error', err)
|
|
|
|
.pipe(outStream)
|
|
|
|
.on('error', err)
|
2019-04-03 00:25:12 +02:00
|
|
|
|
2020-05-14 22:36:58 +02:00
|
|
|
outStream.on('finish', () => {
|
2019-04-03 00:25:12 +02:00
|
|
|
cb(null, {
|
2019-06-11 17:44:11 +02:00
|
|
|
destination: config.upload_path,
|
2019-04-03 00:25:12 +02:00
|
|
|
filename,
|
|
|
|
path: finalPath,
|
|
|
|
size: outStream.bytesWritten
|
|
|
|
})
|
|
|
|
})
|
2019-06-11 17:44:11 +02:00
|
|
|
},
|
2019-09-11 19:12:24 +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
|