1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- var actions = require("./action/index");
- module.exports = function(request, response) {
- var pathname = request.pathname;
-
- if(request.method === 'OPTIONS') {
- response.end();
- }else if(actions.hasOwnProperty(pathname)) {
- if(pathname === '/file/upload') {
- response.writeHead(200, {
- "Content-Type": "application/json;charset=UTF-8"
- });
- var pr = actions[pathname](request, response);
- pr.then(data => {
- response.write(JSON.stringify({
- code: 200,
- success: true,
- data: data
- }));
- response.end();
- }).catch((err) => {
- response.write(JSON.stringify({
- code: 200,
- success: false,
- data: null,
- msg: err
- }));
- response.end();
- });
- }else if(pathname === '/file/download') {
- var filename = request.query.filename;
- var arr = [];
-
- var readStream = actions[pathname](request, response);
-
- readStream.on('data', chunk => {
- arr.push(Buffer.from(chunk));
- });
- readStream.on('error', err => {
- response.writeHead(200, {
- "Content-Type": "application/json;charset=UTF-8"
- });
- response.write(JSON.stringify({
- code: 200,
- success: false,
- msg: err,
- data: null
- }));
- response.end();
- });
- readStream.on('end', () => {
- response.writeHead(200, {
- "Content-Type": "application/octet-stream",
- 'Content-Disposition': 'attachment; filename=' + encodeURI(filename)
- });
- response.write(Buffer.from(...arr), 'binary');//文档内容以二进制的格式写到response的输出流
- response.end();
- })
- }else {
- response.writeHead(200, {
- "Content-Type": "application/json;charset=UTF-8"
- });
- response.write(JSON.stringify({
- code: 200,
- success: true,
- data: actions[pathname](request, response)
- }));
- response.end();
- }
- }else {
- response.write(JSON.stringify({
- code: 200,
- success: false,
- msg: 'no matches.',
- data: null
- }));
- response.end();
- }
- }
|