upload.js
2.4 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
86
87
88
89
90
91
92
/**
* 公共接口
* @author: jinhu.dong<jinhu.dong@yoho.cn>
* @date: 2016/07/21
*/
'use strict';
const request = require('request');
const fs = require('fs');
// 获取图片绝对地址
const getImgHost = (url) => {
let domain = 'static.yhbimg.com/goodsimg',
urlArr = url.split('/'),
num = urlArr[urlArr.length - 1].substr(1, 1),
url1 = domain + url;
if (num === '1') {
return 'http://img11.' + url1;
} else {
return 'http://img12.' + url1;
}
};
// 上传图片
const uploadImg = (req, res) => {
let i = 0;
let files;
let imgs, datas;
if (req.user.uid) {
files = [req.files.filename];
// 如果是单张,则数组化
if (Object.prototype.toString.call(files) !== '[object Array]') {
files = [req.files.filename];
}
req.body.files = [];
req.body.fileNames = [];
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
req.body.files[fileIndex] = fs.createReadStream(files[fileIndex].path);
req.body.fileNames[fileIndex] = files[fileIndex].name;
}
if (req.body.bucket === 'goodsimg') {
request.post({
url: 'http://upload.static.yohobuy.com',
formData: {
fileData: req.body.files,
project: req.body.bucket
},
json: true
}, (error, httpResponse, rebody) => {
if (!error && httpResponse.statusCode === 200) {
imgs = rebody.data.imagesList || [];
datas = [];
// 生成图片绝对地址
for (i = 0; i < imgs.length; i++) {
datas.push(getImgHost(imgs[i]));
}
}
res.json({
code: 200,
data: datas[0],
datas: datas,
names: req.body.fileNames,
message: '上传成功',
status: true
});
});
} else {
res.json({
code: 500,
message: '上传图片失败, 请稍后重试!'
});
}
} else {
res.json({
code: 401,
message: '用户失效,请重新登录'
});
}
};
module.exports = {
uploadImg
};