Bước 1: Tạo service upload ảnh
const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
var file = require('file-system');
const fs = require('fs')
const dir = './public'
let sub = moment(moment.now()).format('YYYY-MM');
/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/' + sub)
},
filename: function (req, file, cb) {
let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g, '_'))
}
})
/** Upload files */
let upload = multer({ storage: storage }).array('files')
/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
let deferred = q.defer()
/** Create dir if not exist */
if (!fs.existsSync(dir + "/" +sub)) {
fs.mkdirSync(dir + "/" + sub)
console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
}
upload(req, res, function (err) {
if (req && (_.isEmpty(req.files))) {
deferred.resolve({ status: 200, message: 'File not attached', data: [] })
} else {
if (err) {
deferred.reject({ status: 400, message: 'error', data: err })
} else {
deferred.resolve({
status: 200,
message: 'File attached',
filename: _.pluck(req.files,
'filename'),
data: req.files
})
}
}
})
return deferred.promise
}
}
Bước 2: Tạo route API về controller : fileUploadController.js
var fileUploadService = require('../services/fileUploadService');
function fileUploadController() {
// var fileUploadService = _fileUploadService();
async function uploadFile(req, res) {
fileUploadService.fileUpload(req, res)
.then(fileUploadServiceResponse => {
res.status(200).send(fileUploadServiceResponse)
})
.catch(error => {
res.status(400).send(error)
})
}
// async function uploadFile(req, res, next) {
// console.log(req);
// if(req.file == null){
// return res.send("Không Có hình")
// } else {
// return res.send("Có hình")
// }
// }
return {
uploadFile: uploadFile
}
}
module.exports = fileUploadController;
Bước 3: Check lại với postman
0 nhận xét:
Đăng nhận xét