|
@@ -1,5 +1,9 @@
|
|
|
import fetch from 'node-fetch';
|
|
|
import Ids from '../models/ids'
|
|
|
+import formidable from 'formidable'
|
|
|
+import path from 'path'
|
|
|
+import fs from 'fs'
|
|
|
+import gm from 'gm'
|
|
|
|
|
|
export default class BaseComponent {
|
|
|
constructor(){
|
|
@@ -49,6 +53,12 @@ export default class BaseComponent {
|
|
|
}
|
|
|
//获取id列表
|
|
|
async getId(type){
|
|
|
+ const typeList = ['orderId', 'userId', 'addressId', 'cartId', 'imgId'];
|
|
|
+ if (!typeList.includes(type)) {
|
|
|
+ console.log('id类型错误');
|
|
|
+ throw new Error('id类型错误');
|
|
|
+ return
|
|
|
+ }
|
|
|
try{
|
|
|
const idData = await Ids.findOne();
|
|
|
idData[type] ++ ;
|
|
@@ -57,5 +67,43 @@ export default class BaseComponent {
|
|
|
}catch(err){
|
|
|
throw new Error(err)
|
|
|
}
|
|
|
+ }
|
|
|
+
|
|
|
+ async uploadImg(req, type = 'default'){
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ const form = formidable.IncomingForm();
|
|
|
+ form.uploadDir = './public/img/' + type;
|
|
|
+ form.parse(req, async (err, fields, files) => {
|
|
|
+ let imgId;
|
|
|
+ try{
|
|
|
+ imgId = await this.getId('imgId');
|
|
|
+ }catch(err){
|
|
|
+ console.log('获取图片id失败');
|
|
|
+ fs.unlink(files.file.path)
|
|
|
+ reject(err);
|
|
|
+ }
|
|
|
+ const imgUrl = new Date().getTime().toString() + imgId;
|
|
|
+ const extname = path.extname(files.file.name);
|
|
|
+ const repath = './public/img/' + type + '/' + imgUrl + extname;
|
|
|
+ try{
|
|
|
+ await fs.rename(files.file.path, repath);
|
|
|
+ gm(repath)
|
|
|
+ .resize(400, 400, '!')
|
|
|
+ .write(repath, async (err) => {
|
|
|
+ if(err){
|
|
|
+ console.log('改写图片尺寸失败');
|
|
|
+ fs.unlink(repath);
|
|
|
+ reject(err);
|
|
|
+ }else{
|
|
|
+ resolve(repath.replace(/^\.\/public/, ''));
|
|
|
+ }
|
|
|
+ })
|
|
|
+ }catch(err){
|
|
|
+ console.log('改写图片路径失败');
|
|
|
+ fs.unlink(files.file.path)
|
|
|
+ reject(err);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ })
|
|
|
}
|
|
|
}
|