file-controller.js
2.75 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* 文件相关controller
* @author: feng.chen<feng.chen@yoho.cn>
* @date: 2017/04/13
*/
'use strict';
const Context = require('../framework/context');
const FileService = require('../service/file-service');
const XlsxService = require('../service/xlsx-service');
const Api = require('../common/api');
const apiDomain = require('../common/api-domain');
const fs = require('fs');
const _ = require('lodash');
class FileController extends Context {
constructor() {
super();
this.api = this.instance(Api);
this.fileService = this.instance(FileService);
this.xlsxService = this.instance(XlsxService);
}
uploadImage(req, res, next) {
let files = (req.files && req.files.file) || [];
let errTip = null;
if (!_.isArray(files)) {
files = [files];
}
req.body.files = [];
const bucket = req.body.bucket;
_.each(files, file => {
const types = file.type.split('/');
if (bucket === 'invoices') {
// 上传 pdf, pdf大小限制500k
const isPDF = /pdf/i.test(file.type || '');
if (!isPDF) {
errTip = '上传文件格式不正确';
}
if (file.size > 500 * 1024) {
errTip = '上传文件尺寸太大!';
}
} else {
if (!types || types[0] !== 'image') {
errTip = '上传文件格式不正确!';
}
// 10M
if (file.size > 10 * 1024 * 1024) {
errTip = '上传文件尺寸太大!';
}
}
if (errTip) {
return false; // return early
}
req.body.files.push(fs.createReadStream(file.path));
req.body.files.push(file.name);
});
if (errTip) {
return res.status(403).send({
message: errTip,
});
}
if (bucket === 'goodsimg' || bucket === 'invoices') {
this.api
.upload('http://upload.static.yohobuy.com', {
fileData: req.body.files,
project: bucket,
})
.then(result => {
if (result.code === 200 && _.get(result, 'data.imagesList.length', 0)) {
result.data.imagesList = _.map(result.data.imagesList, imgUrl => {
return this.fileService.getAbsoluteUrl(imgUrl, bucket);
});
}
res.json(result);
})
.catch(next);
} else {
this.api
.upload(apiDomain.platform.uploads, {
files: req.body.files,
bucket,
})
.then(result => {
const newResult = {
code: result.code,
data: {},
message: result.message,
};
if (result.code === 200) {
newResult.data.imagesList = [result.data[0]];
}
res.json(newResult);
})
.catch(next);
}
}
}
module.exports = FileController;