2018-03-17 21:14:50 -04:00
|
|
|
'use strict'
|
2018-12-18 08:52:09 -05:00
|
|
|
const URL = require('url').URL
|
2018-09-26 14:40:28 -04:00
|
|
|
const path = require('path')
|
2020-12-27 09:52:26 -05:00
|
|
|
const fs = require('fs')
|
2018-03-17 21:14:50 -04:00
|
|
|
|
|
|
|
const config = require('../../config')
|
2018-06-01 07:01:57 -04:00
|
|
|
const logger = require('../../logger')
|
2018-03-17 21:14:50 -04:00
|
|
|
|
|
|
|
exports.uploadImage = function (imagePath, callback) {
|
2019-06-08 14:51:24 -04:00
|
|
|
if (!callback || typeof callback !== 'function') {
|
|
|
|
logger.error('Callback has to be a function')
|
2018-03-17 21:14:50 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-08 14:51:24 -04:00
|
|
|
if (!imagePath || typeof imagePath !== 'string') {
|
|
|
|
callback(new Error('Image path is missing or wrong'), null)
|
2018-03-17 21:14:50 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-27 09:52:26 -05:00
|
|
|
const fileName = path.basename(imagePath)
|
|
|
|
// move image from temporary path to upload directory
|
|
|
|
try {
|
|
|
|
fs.copyFileSync(imagePath, path.join(config.uploadsPath, fileName))
|
|
|
|
} catch (e) {
|
|
|
|
callback(new Error('Error while moving file'), null)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
callback(null, (new URL(fileName, config.serverURL + '/uploads/')).href)
|
2018-03-17 21:14:50 -04:00
|
|
|
}
|