后台是Node 代码如下:
let express=require("express"); var bodyParser = require("body-parser");//解析post参数,并注入到req.body中; let fs= require("fs"); let multer = require("multer");//上传文件的模块 let upload =multer({dest:"./imgs"});//设置图片保存路径 let app=express(); let sql=require("./sql") app.use(bodyParser.urlencoded({ extended: false })) app.use("/",express.static("html"));//设置静态服务器; app.post("/img",upload.single('file'),(req,res)=>{ // console.log(res.body); let file = req.file; let imgurl="./html/imgs/"+file.originalname fs.rename(file.path,imgurl,(err)=>{ if(!err){ sql.sync().then(()=>{ return sql.findOrCreate({ where:{ imgurl:"http://localhost:3010/imgs/"+file.originalname } }) }).then(([user,created])=>{ console.log(user) res.send(user) }) //此时将文件名存到数据库; } }); //将上传的文件重命名,并且移动到新位置 }) app.listen(3010)sql模块:
const Sequelize = require('sequelize'); const sequelize = new Sequelize('nodesql', 'root', 'root', { host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, }); const User = sequelize.define('img', { imgurl: { type: Sequelize.STRING }, }); module.exports=User;这就实现了前端上传的图片,后台处理后将图片存储,将图片的url保存在数据库,并且返回到前端; 简单记录,已备使用