1 | var express = require("express");
|
2 | var app = express();
|
3 | var autoroute = require("express-autoroute");
|
4 | var http = require("http");
|
5 | var bodyParser = require('body-parser');
|
6 | var methodOverride = require('method-override');
|
7 | var path = require("path");
|
8 | var zxy = require('zxy-comm');
|
9 | var multer = require('multer');
|
10 | var uploadPath = path.join(__dirname, '../../../uploads');
|
11 | var upload = multer({ dest: uploadPath });
|
12 |
|
13 | var _ = require('underscore');
|
14 | var Promise = require('bluebird');
|
15 | var fs = require('fs');
|
16 | var multiparty = require('multiparty');
|
17 |
|
18 |
|
19 | var runExpress = function (conf, middleware) {
|
20 | if (conf && conf.port) {
|
21 | app.configure(function () {
|
22 | app.set('port', conf.port);
|
23 | if (conf.static) {
|
24 | app.use(express.static(conf.static));
|
25 | }
|
26 | var defaultStaticPath = path.join(__dirname, '../frame structure demo/static');
|
27 | app.use('/express', express.static(defaultStaticPath));
|
28 | app.use(bodyParser.urlencoded({
|
29 | extended: true
|
30 | }));
|
31 | app.use(bodyParser.json());
|
32 | app.use(bodyParser.text({
|
33 | type: 'text/xml'
|
34 | }));
|
35 | app.use(bodyParser.text());
|
36 | app.use(methodOverride());
|
37 | app.use(function (req, res, next) {
|
38 | res.setHeader("Access-Control-Allow-Origin", "*");
|
39 | res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
|
40 | res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
|
41 | var _method = req.method;
|
42 | var _querystring = req.query;
|
43 | var _pid = process.pid;
|
44 | var _router = req.path;
|
45 | req._request = {
|
46 | method: _method,
|
47 | querystring: _querystring,
|
48 | pid: _pid,
|
49 | router: _router
|
50 | };
|
51 | if (_router == '/zxy-upload' && _method.toUpperCase() == "OPTIONS" ||
|
52 | _router == '/zxy-upload' && _method.toUpperCase() == "POST" ||
|
53 | _router.StartWith('/zxy-download/') && _method.toUpperCase() == "GET") {
|
54 | next();
|
55 | }
|
56 | else {
|
57 | req.setEncoding('utf-8');
|
58 | if (middleware && typeof middleware == 'function') {
|
59 | middleware(req, res, function () {
|
60 | output(req, next, _pid);
|
61 | });
|
62 | }
|
63 | else {
|
64 | output(req, next, _pid);
|
65 | }
|
66 | }
|
67 | });
|
68 | });
|
69 | autoroute(app, { throwErrors: true });
|
70 | http.createServer(app).listen(app.get('port'), function () {
|
71 | var singleCoreProcess;
|
72 | if (process.argv) {
|
73 | if (process.argv.length) {
|
74 | singleCoreProcess = process.argv[process.argv.length - 1].indexOf('-d') == 0 ? true : false
|
75 | }
|
76 | else {
|
77 | singleCoreProcess = process.argv[0].indexOf('-d') == 0 ? true : false
|
78 | }
|
79 | }
|
80 | if (singleCoreProcess) {
|
81 | if (zxy.app.f_job) {
|
82 | if (zxy.app.m_verify.isArray(zxy.app.f_job)) {
|
83 | _.each(zxy.app.f_job, function (job) {
|
84 | if (zxy.app.m_verify.isJson(job)) {
|
85 | var job = new require('./comm/job').jobObj(job.conf, job.func, job.params, job.name);
|
86 | }
|
87 | });
|
88 | }
|
89 | }
|
90 | var serverIp = zxy.app.m_obtain.getServerIP();
|
91 | console.info('a single core process[' + process.pid + '] listening on', serverIp, ':', app.get('port'));
|
92 | }
|
93 | });
|
94 | app.post('/zxy-upload', function (req, res, next) {
|
95 | res.setHeader("Access-Control-Allow-Origin", "*");
|
96 |
|
97 | var form = new multiparty.Form();
|
98 |
|
99 | form.encoding = 'utf-8';
|
100 |
|
101 | form.uploadDir = "uploads/";
|
102 |
|
103 |
|
104 |
|
105 |
|
106 | form.parse(req, function (err, fields, files) {
|
107 | var destination = path.join(__dirname, '../../../uploads/');
|
108 | var encoding = form.encoding;
|
109 | var batch = zxy.app.m_cryptogram.md5(new Date().valueOf().toString() + zxy.app.m_obtain.getRandomStr() + zxy.app.m_obtain.guid());
|
110 | var ids = new Array();
|
111 | var promise_arr = new Array();
|
112 | _.each(files, function (obj) {
|
113 | obj = obj[0];
|
114 | var id = zxy.app.m_obtain.guid();
|
115 | var originalname = obj.originalFilename;
|
116 | ids.push({ uuid: id, file: originalname });
|
117 | var fieldname = obj.fieldName;
|
118 | var filename = obj.path.replace('uploads\\', '').replace('uploads/', '');
|
119 | var mimetype = obj.headers['content-type'];
|
120 | var path = require('path').join(__dirname, '../../../' + obj.path);
|
121 | var size = obj.size;
|
122 | var sql = "INSERT INTO zxy_upload_log("
|
123 | + "id,destination,encoding,fieldname,filename,mimetype,originalname,path,size,upload_time,batch)VALUES("
|
124 | + "@id,@destination,@encoding,@fieldname,@filename,@mimetype,@originalname,@path,@size,NOW(),@batch);";
|
125 | promise_arr.push(
|
126 | zxy.app.m_mysql.run(sql, {
|
127 | id: id,
|
128 | destination: destination,
|
129 | encoding: encoding,
|
130 | fieldname: fieldname,
|
131 | filename: filename,
|
132 | mimetype: mimetype,
|
133 | originalname: originalname,
|
134 | path: path,
|
135 | size: size,
|
136 | batch: batch
|
137 | })
|
138 | );
|
139 | });
|
140 | Promise.all(promise_arr).then(function () {
|
141 | res.jsonp(ids);
|
142 | });
|
143 | });
|
144 | });
|
145 | app.get('/zxy-download/:id', function (req, res, next) {
|
146 | res.setHeader("Access-Control-Allow-Origin", "*");
|
147 | var id = req.params.id;
|
148 | try {
|
149 | var sql = "select * from zxy_upload_log where id = @id";
|
150 | zxy.app.m_mysql.run(sql, {
|
151 | id: id
|
152 | }).then(function (r) {
|
153 | if (r && r.length && r[0]) {
|
154 | if (fs.exists(r[0].path, function (exists) {
|
155 | if (exists) {
|
156 | if (r[0].mimetype.StartWith('image/')) {
|
157 | var rs = fs.createReadStream(r[0].path);
|
158 | rs.on('data', function (data) {
|
159 | res.write(data);
|
160 | });
|
161 | rs.on('end', function () {
|
162 | res.end();
|
163 | });
|
164 | }
|
165 | else {
|
166 | var attachmentName = r[0].originalname;
|
167 | attachmentName = encodeURIComponent(attachmentName);
|
168 | res.setHeader('Content-disposition', 'attachment; filename=' + attachmentName);
|
169 | res.setHeader('Content-type', r[0].mimetype + ";charset=utf8");
|
170 | var filestream = fs.createReadStream(r[0].path);
|
171 | filestream.on('data', function (chunk) {
|
172 | res.write(chunk);
|
173 | });
|
174 | filestream.on('end', function () {
|
175 | res.end();
|
176 | });
|
177 | }
|
178 | }
|
179 | else {
|
180 | res.send({ code: -1, msg: '文件不存在' });
|
181 | }
|
182 | }));
|
183 | }
|
184 | else {
|
185 | res.send({ code: -2, msg: '文件信息不存在' });
|
186 | }
|
187 | }).catch(function () {
|
188 | res.send({ code: -3, msg: '查找文件信息异常' });
|
189 | });
|
190 | }
|
191 | catch (ex) {
|
192 | res.send({ code: -4, msg: '系统错误' });
|
193 | }
|
194 | });
|
195 | }
|
196 | }
|
197 | exports.runExpress = runExpress;
|
198 |
|
199 | function l(req, pid) {
|
200 | setTimeout(function () {
|
201 | if (req.path != "/favicon.ico" && req.method.toLowerCase() != "options") {
|
202 | var method = req.method,
|
203 | path = req.path,
|
204 | params = req.params ? zxy.app.m_convert.objToStr(req.params) : "",
|
205 | query = req.query ? JSON.stringify(req.query) : "",
|
206 | body = req.body ? (zxy.app.m_verify.isJson(req.body) ? JSON.stringify(req.body) : req.body.toString()) : "",
|
207 | headers = req.headers ? JSON.stringify(req.headers) : "",
|
208 | clientip = zxy.app.m_obtain.getClientIP(req).replace('::ffff:', '');
|
209 |
|
210 |
|
211 |
|
212 | console.info(method, "| ", path, "| ClientIP:", clientip, "| pid:", pid, "| params:", params, "| query:", query, "| body:", body, "| headers:", headers);
|
213 | var sql = "INSERT INTO zxy_api_log VALUES(UUID(),NOW(),@req_ip,@method,@path,@pid,@params,@query,@body,@headers)";
|
214 | zxy.app.m_mysql.run(sql, {
|
215 | req_ip: clientip,
|
216 | method: method,
|
217 | path: path,
|
218 | pid: pid,
|
219 | params: params,
|
220 | query: query,
|
221 | body: body,
|
222 | headers: headers
|
223 | });
|
224 | }
|
225 | }, 0);
|
226 | }
|
227 |
|
228 | function output(req, next, pid) {
|
229 | if (req.method.toLowerCase() === "post") {
|
230 | var _body = "";
|
231 | req.addListener("data", function (postDataChunk) {
|
232 | _body += postDataChunk;
|
233 | });
|
234 | req.addListener("end", function () {
|
235 | req.body = _body;
|
236 | next();
|
237 | l(req, pid);
|
238 | });
|
239 | }
|
240 | else {
|
241 | next();
|
242 | l(req, pid);
|
243 | }
|
244 | } |
\ | No newline at end of file |