/*
* @Descripttion:
* @version:
* @Author: sueRimn
* @Date: 2020-07-07 11:33:19
* @LastEditors: sueRimn
* @LastEditTime: 2020-07-09 16:06:53
*/
var express = require('express');
var router = express.Router();
const multer = require('multer');
const co = require('co');
const fs = require('fs')
let User = require('../controller/usercontroller');
const MAO = require('multer-aliyun-oss');
let OSS = require('ali-oss')
let client = new OSS({
region: '',
accessKeyId: '',
accessKeySecret: ',
});
var ali_oss = {
bucket: '',
endPoint: '',
}
let upload = multer({ dest: './upload' }).single('filename')
router.post('/upload', upload, async (req, res) => {
// 文件路径
var filePath = './' + req.file.path;
// 文件类型
var temp = req.file.originalname.split('.');
var fileType = temp[temp.length - 1];
var lastName = '.' + fileType;
console.log(lastName)
// 构建图片名
var fileName = Date.now() + lastName;
// 图片重命名
fs.rename(filePath, fileName, (err) => {
if (err) {
res.end(JSON.stringify({ status: '102', msg: '文件写入失败' }));
} else {
var localFile = './' + fileName;
var key = fileName;
console.log(key)
// console.log(localFile)
// 阿里云 上传文件
co(function* () {
console.log(client)
client.useBucket(ali_oss.bucket);
console.log(key, localFile)
var result = yield client.put('images/' + key, localFile,{
//这一步是为了解决返回的图片直接默认打开的需要做判断处理由于时间关系所以暂无处理
headers:{
'content-type':'image/jpg'
}
});
var imageSrc = '你自己的阿里云域名地址' + result.name;
// 上传之后删除本地文件
fs.unlinkSync(localFile);
res.end(JSON.stringify({ status: '100', msg: '上传成功', imageUrl: imageSrc }));
}).catch(function (err) {
// 上传之后删除本地文件
fs.unlinkSync(localFile);
res.end(JSON.stringify({ status: '101', msg: '上传失败', error: JSON.stringify(err) }));
});
}
});
})
router.get('/login', User.loginUser)
router.get('/getUser', User.getUSer)
module.exports = router;