vue+axios+nodejs上传图片

一,(方式一)上传到项目静态文件夹

Multer 是一个 node.js 中间件,用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件。

注意: Multer 不会处理任何非 multipart/form-data 类型的表单数据。

 

前端代码:

<div class="head">
        <img
          :src="head_img || '/static/images/read.png'"
          alt=""
          @click="showSheet"
        />
        <input
          ref="uploadImg"
          type="file"
          @change="changeFile"
          class="uploadImg"
          accept="image/*"
        />
      </div>

  

changeFile(e) {
      let file = e.target.files[0];
      let formData = new FormData();
      formData.append("avatar", file);
      formData.append("userId", this.info.id);

      this.$axios
        .post(`/uploadImg`, formData, {
          onUploadProgress: (progressEvent) => {    //axios上传文件的进程方法,可以翻api
            //这里要用箭头函数,不然这个this的指向会有问题
            this.rate = parseInt(
              (progressEvent.loaded / progressEvent.total) * 100
            );
          },
        })
        .then((res) => {
          if (res.data.state == "success") {
            this.$store.dispatch("getInfo", res.data.data);
            this.info = JSON.parse(localStorage.getItem('userInfo'));
            setTimeout(() => {
              this.$toast(res.data.msg);
            }, 500);
          } else {
            this.$toast({
              message: res.data.msg,
              iconClass: "icon icon-fail",
            });
          }
        });
    },

  

后端代码:

const multer = require('multer')		//express框架上传文件所需要的中间件
const upload = multer({			//multer中间件的使用方法可以看官网
    dest: './uploads/'
})

  

app.post('/uploadImg',upload.single('avatar'),require('./api/uploadImg')) //上传头像

  

uploadImg.js

const connect = require('../db');

const fs = require('fs');
const uploadImg = (req, res) => {
    let fileName = "";
    const userId = req.body.userId;

    if (req.file != undefined) {
        fileName = new Date().getTime() + "_" + req.file.originalname;

        const oldPath = req.file.path;
        const newPath = "uploads/img/" + fileName;
        fs.rename(oldPath,newPath, err => {//重命名,加后缀,不然图片会显示乱码,打不开
            if (err) console.log(err);
            insertUserInfo(userId,newPath,res);
        }); 
    }
}

//将头像地址放到数据库
function insertUserInfo(id,path,res) {
    connect(`update user_info set head_img = '${path}' where id =${id}`,(err,results,fileds)=>{
        if(err) throw err;
        //更新成功
        if(results.affectedRows === 1){
            //更新用户信息返回前端
            connect(`select * from user_info where id = '${id}'`,function (err,results,feild) {
                if(err) throw err;
                if(results.length === 1){
                    res.send({state:'success',msg:'上传成功',data:results[0]});
                }else{
                    res.send({state:'fail',msg:'发生错误',data:null});
                }
            })
        }else{
            res.send({state:'fail',msg:'发生错误',data:null});
        }
    })
}

module.exports = uploadImg

  

传入的文件在req.file中,其他的字段在req.body中

 

二,(方式二)转为base64格式存到数据库

将图片转为base64当作字段值存入数据库

前端代码:

<div class="head">
        <img
          :src="head_img || '/static/images/read.png'"
          alt=""
          @click="showSheet"
        />
        <input
          ref="uploadImg"
          type="file"
          @change="changeFile"
          class="uploadImg"
          accept="image/*"
        />

  

changeFile(e) {
      let file = e.target.files[0];
      let that = this;
      let base64 = "";
      let reader = new FileReader();
      reader.onload = (function (file) {
        return function (e) {
          base64 = this.result; //这个就是base64的数据了

          //存入数据库
          that.$axios
            .post("/uploadBase64", { base64: base64, userId: that.info.id })
            .then((res) => {
              if (res.data.state == "success") {
                that.$store.dispatch("getInfo", res.data.data);
                that.info = JSON.parse(localStorage.getItem('userInfo'));
                setTimeout(() => {
                  that.$toast(res.data.msg);
                }, 500);
              } else {
                that.$toast({
                  message: res.data.msg,
                  iconClass: "icon icon-fail",
                });
              }
            });
        };
      })(file);
      reader.readAsDataURL(file);
    },

  

后端就正常的用post请求接受参数,将整个base64码存到数据库即可

 

posted @ 2020-12-01 19:24  北巷听雨  阅读(557)  评论(0编辑  收藏  举报
返回顶端