乐趣区

关于node.js:NodejsExpress后端实现上传文件并保存到数据库

NodeJS 全栈开发之后端实现上传文件性能并保留到 Mysql 数据库

装置第三方插件 multer
npm i –save multer

创立上传接口文件 upload.js
var createFolder = function(folder){

try{fs.accessSync(folder); 
}catch(e){fs.mkdirSync(folder);
}  

};
var uploadFolder = ‘./uploads/’; // 文件上传地位

createFolder(uploadFolder);
var storage = multer.diskStorage({

destination: function (req, file, cb) {cb(null, uploadFolder)
},
filename: function (req, file, cb) {cb(null, file.originalname)
}

})

var upload = multer({storage: storage})

// 上传接口
router.post(‘/upload’, upload.single(‘file’), function(req, res) {

fs.rename(req.file.path, "uploads/" + req.file.originalname, function(err) {if (err) {throw err;}
    var data= req.file
    var photo=req.file.url
    res.send({
        code:CODE_SUCCESS,
        msg:'上传胜利',
        data:data
      })
   // 增加到数据库
    const query = `insert into sys_data(photo) values('${photo}')`;
    querySql(query)
    .then(data => {

      res.json({ 
          code: CODE_SUCCESS, 
          msg: '增加数据胜利', 
          data: null 
        })
    })
 })

})

module.exports = router

通过 postman 测试上传接口

退出移动版