2018-03-18 01:14:50 +00:00
|
|
|
'use strict'
|
|
|
|
|
2020-05-30 16:41:01 +00:00
|
|
|
const fs = require('fs')
|
2020-12-23 07:46:19 +00:00
|
|
|
const path = require('path')
|
2018-03-18 01:14:50 +00:00
|
|
|
const Router = require('express').Router
|
|
|
|
const formidable = require('formidable')
|
|
|
|
|
2020-12-22 08:48:13 +00:00
|
|
|
const readChunk = require('read-chunk')
|
|
|
|
const imageType = require('image-type')
|
2020-12-23 07:46:19 +00:00
|
|
|
const mime = require('mime-types')
|
2020-12-22 08:48:13 +00:00
|
|
|
|
2020-01-04 22:30:23 +00:00
|
|
|
const config = require('../config')
|
|
|
|
const logger = require('../logger')
|
|
|
|
const response = require('../response')
|
2018-03-18 01:14:50 +00:00
|
|
|
|
|
|
|
const imageRouter = module.exports = Router()
|
|
|
|
|
2020-12-22 08:48:13 +00:00
|
|
|
function checkImageValid (filepath) {
|
|
|
|
const buffer = readChunk.sync(filepath, 0, 12)
|
2020-12-23 07:46:19 +00:00
|
|
|
/** @type {{ ext: string, mime: string } | null} */
|
|
|
|
const mimetypeFromBuf = imageType(buffer)
|
|
|
|
const mimeTypeFromExt = mime.lookup(path.extname(filepath))
|
|
|
|
|
|
|
|
return mimetypeFromBuf && config.allowedUploadMimeTypes.includes(mimetypeFromBuf.mime) &&
|
|
|
|
mimeTypeFromExt && config.allowedUploadMimeTypes.includes(mimeTypeFromExt)
|
2020-12-22 08:48:13 +00:00
|
|
|
}
|
|
|
|
|
2018-03-18 01:14:50 +00:00
|
|
|
// upload image
|
|
|
|
imageRouter.post('/uploadimage', function (req, res) {
|
|
|
|
var form = new formidable.IncomingForm()
|
|
|
|
|
|
|
|
form.keepExtensions = true
|
|
|
|
|
|
|
|
form.parse(req, function (err, fields, files) {
|
|
|
|
if (err || !files.image || !files.image.path) {
|
2020-02-26 03:13:45 +00:00
|
|
|
response.errorForbidden(req, res)
|
2018-03-18 01:14:50 +00:00
|
|
|
} else {
|
|
|
|
if (config.debug) {
|
|
|
|
logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image))
|
|
|
|
}
|
|
|
|
|
2020-12-22 08:48:13 +00:00
|
|
|
if (!checkImageValid(files.image.path)) {
|
|
|
|
return response.errorForbidden(req, res)
|
|
|
|
}
|
|
|
|
|
2018-03-07 14:17:35 +00:00
|
|
|
const uploadProvider = require('./' + config.imageUploadType)
|
2018-03-18 01:14:50 +00:00
|
|
|
uploadProvider.uploadImage(files.image.path, function (err, url) {
|
2020-05-30 16:41:01 +00:00
|
|
|
// remove temporary upload file, and ignore any error
|
|
|
|
fs.unlink(files.image.path, () => {})
|
2018-03-18 01:14:50 +00:00
|
|
|
if (err !== null) {
|
|
|
|
logger.error(err)
|
|
|
|
return res.status(500).end('upload image error')
|
|
|
|
}
|
|
|
|
res.send({
|
|
|
|
link: url
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|