|
| 1 | +'use strict' |
| 2 | +const fs = require('fs') |
| 3 | +const path = require('path') |
| 4 | + |
| 5 | +const config = require('../../config') |
| 6 | +const {getImageMimeType} = require('../../utils') |
| 7 | + |
| 8 | +const Minio = require('minio') |
| 9 | +const minioClient = new Minio.Client({ |
| 10 | + endPoint: config.minio.endPoint, |
| 11 | + port: config.minio.port, |
| 12 | + secure: config.minio.secure, |
| 13 | + accessKey: config.minio.accessKey, |
| 14 | + secretKey: config.minio.secretKey |
| 15 | +}) |
| 16 | + |
| 17 | +exports.uploadImage = function (imagePath, callback) { |
| 18 | + if (!imagePath || typeof imagePath !== 'string') { |
| 19 | + callback(new Error('Image path is missing or wrong'), null) |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + if (!callback || typeof callback !== 'function') { |
| 24 | + callback(new Error('Callback has to be a function'), null) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + fs.readFile(imagePath, function (err, buffer) { |
| 29 | + if (err) { |
| 30 | + callback(new Error(err), null) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + let key = path.join('uploads', path.basename(imagePath)) |
| 35 | + let protocol = config.minio.secure ? 'https' : 'http' |
| 36 | + |
| 37 | + minioClient.putObject(config.s3bucket, key, buffer, buffer.size, getImageMimeType(imagePath), function (err, data) { |
| 38 | + if (err) { |
| 39 | + callback(new Error(err), null) |
| 40 | + return |
| 41 | + } |
| 42 | + callback(null, `${protocol}://${config.minio.endPoint}:${config.minio.port}/${config.s3bucket}/${key}`) |
| 43 | + }) |
| 44 | + }) |
| 45 | +} |
0 commit comments