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

1 篇文章 0 订阅
1 篇文章 0 订阅

前端代码

<!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;

  

文件目录结构

项目总目录html文件夹
这就实现了前端上传的图片,后台处理后将图片存储,将图片的url保存在数据库,并且返回到前端;
简单记录,已备使用

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值