如何使用multer从上传的文件向MySQL插入表行?

时间:2019-05-25 10:12:54

标签: mysql node.js multer

我正在将带有multer的文件上传到“上传”文件夹。在上载时,我正在尝试将文件的“ JSON”数据插入MySQL表。使用req.file,我似乎只获得有关上载文件,mimetype,目标位置,路径等的信息。如何访问文件内部的数据并将其存储到不同的表行中?

app.post('/uploadjson', (req, res) => {
    upload3(req, res, (err) => {
        if(err){
            res.render('index', {
                msg: err
            });
        } else {
            if(req.file == undefined){
                res.render('index', {
                    msg: 'Error: No File Selected!'
                });
            } else {
                db.query('INSERT INTO study_modules (id, studyProgramme, subgroup, title, start, end, classroom, type, weekday) VALUES ?', [req.file], function(err, res){
                    if(err) throw err;
                    console.log("Success");
                });
            }
        }
    });
});

数据库表结构:

CREATE TABLE `study_modules` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `studyProgramme` varchar(255) NOT NULL,
  `subgroup` varchar(8) NOT NULL,
  `title` varchar(255) NOT NULL,
  `start` varchar(19) NOT NULL,
  `end` varchar(19) NOT NULL,
  `classroom` varchar(5) NOT NULL,
  `type` varchar(8) NOT NULL,
  `weekday` varchar(9) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=133 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

上传文件的结构:

[
    {
        "id": 5,
        "studyProgramme": "MIT",
        "subgroup": "MIT 1-6",
        "title": "Computer Science",
        "start": "1995-12-17T16:30",
        "end": "1995-12-17T18:30",
        "classroom": "503a.",
        "type": "Lecture",
        "weekday": "Monday"
    },
    {
        "id": 6,
        "studyProgramme": "IF",
        "subgroup": "IF 1-6",
        "title": "Object Oriented Programming",
        "start": "1995-12-17T14:30",
        "end": "1995-12-17T16:30",
        "classroom": "503a.",
        "type": "Lecture",
        "weekday": "Monday"
    }
]

0 个答案:

没有答案