upload.js
1.63 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
84
85
const fs = require('fs');
const _ = require('lodash');
const request = require('request-promise');
const log = global.yoho.logger;
const upload = ({ files, type, size, bucket }) => {
let reqFiles = [];
let errTip = '';
if (!_.isArray(files)) {
files = [files];
}
size = size || 10 * 1024 * 1024;
files.forEach(file => {
let fileType = file.type.split('/');
if (!fileType || (type && fileType[0] !== type)) {
errTip = '上传文件格式不正确!';
}
if (file.size > size) {
errTip = '上传文件尺寸太大!';
}
if (file.path.indexOf('.') < 0) {
let newPath = `${file.path}.${fileType[1]}`;
fs.renameSync(file.path, newPath);
file.path = newPath;
}
reqFiles.push(fs.createReadStream(file.path));
reqFiles.push(file.name);
});
if (errTip) {
return Promise.resolve({
code: 403,
message: errTip
});
}
return request({
method: 'post',
url: 'http://upload.static.yohobuy.com',
formData: {
fileData: reqFiles,
project: bucket
},
json: true
}).catch(err => {
let message = 'file upload error';
log.error(message, JSON.stringify(err));
return {
code: 403,
message
};
});
}
const uploadIdCard = (req, res, next) => {
upload({
files: req.files && req.files.file || [],
type: 'image',
bucket: 'yohocard'
}).then(res.json).catch(next);
}
const uploadIdIm = (req, res, next) => {
upload({
files: req.files && req.files.file || [],
type: 'image',
bucket: 'imserver'
}).then(res.json).catch(next);
}
module.exports = {
uploadIdCard,
uploadIdIm
};