upload.js
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
const fs = require('fs');
const _ = require('lodash');
const utils = require('../models/utils');
const yohoApi = global.yoho.API;
const AllowedBucket = {
sns: 'sns',
evidenceImages: 'evidenceImages'
};
const uploadImg = (req, res, next) => {
let files = req.files && req.files.file || [];
let errTip = null;
if (!_.isArray(files)) {
files = [files];
}
req.body.files = [];
files.forEach(file => {
let types = file.type.split('/');
if (!types || types[0] !== 'image') {
errTip = '上传文件格式不正确!';
}
if (file.size > 10 * 1024 * 1024) {
errTip = '上传文件尺寸太大!';
}
req.body.files.push(fs.createReadStream(file.path));
});
if (errTip) {
return res.status(403).send({
message: errTip
});
}
const bucket = AllowedBucket[req.body.bucket];
if (!bucket) {
return res.json({
code: 400,
message: '参数错误'
});
}
Promise.all(
req.body.files.map(f => {
return yohoApi.postFile('', {
bucket: req.body.bucket,
file: f,
uid: req.user.uid.toString(),
method: 'yoho.fileupload'
}).then(result => {
if (result.code !== 200) {
return Promise.reject(Error('上传出错'));
}
return result;
});
})
).then(result => {
const data = result.reduce((t, r) => {
t.images.push(utils.getUploadImgAbsoluteUrl(_.get(r, 'data'), req.body.bucket));
t.imagesList.push(_.get(r, 'data'));
return t;
}, { images: [], imagesList: [] });
res.json({
code: 200,
data,
message: '上传成功'
});
}).catch(next);
};
module.exports = {
uploadImg
};