Jelajahi Sumber

修改推荐接口
添加文件上传读写接口

kindring 2 tahun lalu
induk
melakukan
dcd1de3817

+ 4 - 2
app.js

@@ -12,6 +12,9 @@ const adminRouter = require('./routes/admin');
 const captcha = require('./routes/captcha');
 const flight = require('./routes/flight_api');
 const recommend = require('./routes/recommend_api');
+const fileControl = require('./routes/file_api');
+
+
 
 const app = express();
 
@@ -48,8 +51,7 @@ app.use('/api/city/',citysRouter);
 app.use('/api/captcha', captcha);
 app.use('/api/flight', flight);
 app.use('/api/recommend', recommend);
-
-
+app.use('/api/file',fileControl);
 
 app.listen(serverConfig.port, serverConfig.host, ()=>{
   console.warn(`服务启动 server is running to @http://${serverConfig.host}:${serverConfig.port}`);

+ 47 - 0
controller/c_file.js

@@ -0,0 +1,47 @@
+const fs = require('fs');
+const path = require('path');
+const handle = require('../until/handle')
+const field = require('../maps/field')
+const codeMap = require('../maps/rcodeMap')
+const  enumMap = require('../maps/enum')
+const configPath = require('../configs/path.json')
+
+/**
+ * 加载图片列表
+ * @returns {Promise<*>}
+ */
+async function loadImgs(){
+    let [err,files] = await  handle(fs.promises.readdir(configPath.upload))
+    if(err){throw err}
+
+    // 过滤非img内容
+    return files.reduce(((a,c)=>{
+        let ext = path.extname(c);
+        if(enumMap.imageExt.includes(ext)){
+            a.push({
+                fileName:c,
+                path: path.join(configPath.upload,c),
+            })
+        }else{
+
+        }
+        return a
+    }),[])
+}
+
+async function toUpload (files){
+    console.log(files)
+    let file = files.file
+    console.log(file)
+    console.log(file.filepath)
+    console.log(file.originalFilename)
+    let targetPath = path.join(configPath.upload,file.originalFilename);
+    let [err,res] = await handle(fs.promises.rename(file.filepath,targetPath))
+    if(err){throw err}
+    return true;
+}
+
+module.exports = {
+    loadImgs,
+    toUpload
+}

+ 2 - 2
controller/c_recommend.js

@@ -12,8 +12,8 @@ async function list(){
     return result;
 }
 
-async function addRecommend(name,descript,zIndex){
-    let [err,result] = await handle(db_recommend.addRecommend(name,descript,zIndex));
+async function addRecommend(name,descript,zIndex,imgUrl){
+    let [err,result] = await handle(db_recommend.addRecommend(name,descript,zIndex,imgUrl));
     if(err){throw err}
     return result;
 }

+ 6 - 5
database/d_recommend.js

@@ -8,14 +8,15 @@ const checkArgumentsIsEmpty = require('../until/checkArgumentsIsEmpty')
  * @param recommendName 活动名
  * @param discript 推荐描述
  * @param zIndex 排序
+ * @param imgUrl
  * @returns {Promise | Promise<unknown>}
  */
-function addRecommend(recommendName,discript,zIndex = 1){
+function addRecommend(recommendName,discript,zIndex = 1,imgUrl = 'public/upload/bg_weekend.jpg'){
     let sql=``,values=[];
     sql+=`insert into 
-            recommend (recommendName,discript,zIndex) 
-            values(?,?,?);`
-    values.push(recommendName,discript,zIndex)
+            recommend (recommendName,discript,zIndex,bg) 
+            values(?,?,?,?);`
+    values.push(recommendName,discript,zIndex,imgUrl)
     return mysql.pq(sql,values);
 }
 
@@ -160,4 +161,4 @@ module.exports = {
     deleteFlight,
     updateRecommend,
     find
-}
+}

+ 3 - 0
maps/enum.js

@@ -0,0 +1,3 @@
+module.exports = {
+    imageExt: ['.jpg','.jpeg','.png','.gif']
+}

+ 39 - 0
middleware/fileUpload.js

@@ -0,0 +1,39 @@
+const path = require('path');
+const fs = require('fs');
+const formidable = require('formidable')
+const code = require("../maps/rcodeMap");
+const configPath = require('../configs/path.json')
+
+function upload(req,res,next){
+    let form = new formidable.IncomingForm();
+    let allFile = [];
+    form.uploadDir = configPath.tmp;
+    form.type = true;
+    form.on('progress', function(bytesReceived, bytesExpected) { //在控制台打印文件上传进度
+        let progressInfo = {
+            value: bytesReceived, //当前进度
+            total: bytesExpected //总进度
+        };
+        let bar_progress = Math.floor((progressInfo.value / progressInfo.total) * 100);
+        console.log(`当前进度: ${bar_progress}`);
+    }).parse(req, function(err, fields, files) {
+        console.log(fields);
+        console.log(files);
+        if (err) {
+            console.log(`文件接收失败${err}`);
+            res.json({
+                rcode: code.customError,
+                msg: '文件上传失败'
+            })
+        }else{
+            console.log('文件上传成功')
+            console.log(fields)
+            console.log('文件数量'+files.length)
+            req.files = files;
+            req.body = fields;
+            next();
+        }
+    })
+}
+
+module.exports = upload;

+ 50 - 0
package-lock.json

@@ -18,6 +18,11 @@
       "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
       "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
     },
+    "asap": {
+      "version": "2.0.6",
+      "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
+      "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY="
+    },
     "body-parser": {
       "version": "1.20.0",
       "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz",
@@ -154,6 +159,15 @@
       "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
       "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
     },
+    "dezalgo": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.3.tgz",
+      "integrity": "sha1-f3Qt4Gb8dIvI24IFad3c5Jvw1FY=",
+      "requires": {
+        "asap": "^2.0.0",
+        "wrappy": "1"
+      }
+    },
     "ee-first": {
       "version": "1.1.1",
       "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -310,6 +324,24 @@
       "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz",
       "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg=="
     },
+    "formidable": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/formidable/-/formidable-2.0.1.tgz",
+      "integrity": "sha512-rjTMNbp2BpfQShhFbR3Ruk3qk2y9jKpvMW78nJgx8QKtxjDVrwbZG+wvDOmVbifHyOUOQJXxqEy6r0faRrPzTQ==",
+      "requires": {
+        "dezalgo": "1.0.3",
+        "hexoid": "1.0.0",
+        "once": "1.4.0",
+        "qs": "6.9.3"
+      },
+      "dependencies": {
+        "qs": {
+          "version": "6.9.3",
+          "resolved": "https://registry.npmjs.org/qs/-/qs-6.9.3.tgz",
+          "integrity": "sha512-EbZYNarm6138UKKq46tdx08Yo/q9ZhFoAXAI1meAFd2GtbRDhbZY2WQSICskT0c5q99aFzLG1D4nvTk9tqfXIw=="
+        }
+      }
+    },
     "forwarded": {
       "version": "0.2.0",
       "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -371,6 +403,11 @@
       "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
       "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A=="
     },
+    "hexoid": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/hexoid/-/hexoid-1.0.0.tgz",
+      "integrity": "sha512-QFLV0taWQOZtvIRIAdBChesmogZrtuXvVWsFHZTk2SU+anspqZ2vMnoLg7IE1+Uk16N19APic1BuF8bC8c2m5g=="
+    },
     "http-errors": {
       "version": "1.6.3",
       "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz",
@@ -564,6 +601,14 @@
       "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
       "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA=="
     },
+    "once": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+      "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
+      "requires": {
+        "wrappy": "1"
+      }
+    },
     "opentype.js": {
       "version": "0.7.3",
       "resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-0.7.3.tgz",
@@ -812,6 +857,11 @@
       "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
       "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
     },
+    "wrappy": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+      "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
+    },
     "yallist": {
       "version": "4.0.0",
       "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",

+ 3 - 2
package.json

@@ -6,12 +6,13 @@
     "start": "node app.js"
   },
   "dependencies": {
+    "body-parser": "^1.19.1",
     "ejs": "~2.6.1",
     "express": "~4.16.1",
     "express-session": "^1.17.2",
-    "body-parser": "^1.19.1",
-    "mysql2": "^2.3.3",
+    "formidable": "^2.0.1",
     "log4js": "^6.3.0",
+    "mysql2": "^2.3.3",
     "svg-captcha": "^1.4.0"
   }
 }

+ 48 - 0
routes/file_api.js

@@ -0,0 +1,48 @@
+const router = require('express').Router();
+const paramsCheck = require('../middleware/paramsCheck');
+const checkLogin = require('../middleware/checkLogin');
+
+const code = require('../maps/rcodeMap')
+const field = require('../maps/field')
+const progress = require('../maps/progress')
+
+const apiErrHandle = require('../until/apiErrHandle')
+const c_file = require("../controller/c_file");
+const {adminType} = require("../maps/field");
+const fileUpload = require('../middleware/fileUpload')
+/**
+ * 获取文件
+ */
+router.get('/list',async(req,res)=>{
+    try{
+        let results = await c_file.loadImgs();
+        res.json({
+            rcode: code.ok,
+            data: results
+        })
+    }catch (e) {
+        apiErrHandle('fileLoad',res,e);
+    }
+});
+
+/**
+ * 上传文件
+ */
+router.post('/up',
+    fileUpload,
+    async (req,res)=>{
+        try{
+            console.log('接收到文件上传');
+            let results = await c_file.toUpload(req.files);
+            res.json({
+                rcode: code.ok,
+            })
+        }catch (e) {
+            res.status(500)
+            apiErrHandle('fileLoad',res,e);
+        }
+    }
+)
+
+module.exports = router;
+

+ 2 - 2
routes/recommend_api.js

@@ -51,7 +51,7 @@ router.post('/recommend/add',
     }),
     async (req,res)=>{
     try{
-        let results = await c_recommend.addRecommend(req.body.recommendName,req.body.descript ,req.body.zIndex);
+        let results = await c_recommend.addRecommend(req.body.recommendName,req.body.descript ,req.body.zIndex,req.body.imgUrl);
         res.json({
             rcode: code.ok,
             data: results
@@ -94,4 +94,4 @@ router.post('/recommend/flights',
     });
 
 
-module.exports = router;
+module.exports = router;

+ 19 - 0
until/apiErrHandle.js

@@ -0,0 +1,19 @@
+const codeMap = require("../maps/rcodeMap");
+// 日志
+const log = require('../logger').logger('errorHandle', 'info');
+function errHandle(apiStr,res,err){
+    err.rcode = parseInt(err.rcode)
+    if (err.rcode !== codeMap.customError) {
+        console.log(err);
+        log.error(`api:${apiStr}_Error ${err.message||err.msg}`);
+    }
+    // 操作超时
+    if (err.code === 'ESOCKETTIMEDOUT') {
+        err.rcode = codeMap.timeout;
+    }
+    res.json({
+        rcode: err.rcode || codeMap.serverError,
+        msg: err.msg || err.message
+    });
+}
+module.exports = errHandle;