前后端联合实现单图片上传功能(express、multer、sequelize)

    xiaoxiao2022-07-03  113

    前端代码

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="file" multiple id="file"> <button>上传</button> <img src="" alt="" id="img"> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> document.getElementById("file").onchange=function(){ console.log(this.files); let formDate=new FormData();//利用FormDate构造函数激昂文件转换为二进制 formDate.append("file",this.files[0]) axios.post("./img",formDate,{ "headers":{ "Content-Type":"multipart/form-data" } }).then(res=>{ console.log(res) document.getElementById("img").src=res.data.imgurl }) } </script> </body> </html>

    后台代码

    后台是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保存在数据库,并且返回到前端; 简单记录,已备使用

    最新回复(0)