vue+node 图片上传到服务器

vue

<template>
<div class="head-img-wrap">
              <img class="headImg" :src=userInfo.avatar alt="" @click.stop="uploadHeadImg" title="更换头像">
              {{username}}
            </div>
            <input id="input" type="file" accept="image/*" @change="getImg ($event)" class="hiddenInput" style="display: none"/>
</template>

export default {
  name: 'Header',
  data () {
      userInfo: {
        avatar: require('../../assets/timg.jpg')//默认头像
      }
    }
  },
 methods:{
 	 getImg (event) {//上传头像
        console.log(this.userInfo.avatar)
      let userName = this.getCookie('userName')
        this.file = event.target.files[0];  //获取图片信息
        var that = this
        event.preventDefault();
        // 只能通过formData方式来传输
        var formData = new FormData();
        formData.append('file', this.file);
        formData.append('userName', userName);
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
        this.$http.post('http://localhost:3333/image', formData, config).then(function(res) {
            console.log(res.data.code)
           location.reload();//上传成功后刷新
        })
    },
    getImgUrl () { // 获取图片
      let _self = this
      this.$http.get('http://localhost:3333/getImgUrl)
        .then(function (res) {
          console.log(res.data.list[0].img)//upload_a0fba84a1730b041db5d526db87f2435.jpg  这是存在服务器的名字  ,此时要想在本地读取图片,必须加上域名或服务器ip, 如下所示,加上服务器ip
          if(res.data.list[0].img!==null){
                _self.userInfo.avatar = 'http://IP(服务器ip)/img/'+res.data.list[0].img//服务器上的地址
            }
        })
        .catch(function (err) {

        })
    },
 },
  mounted () {
    this.getImgUrl ()
  }
    
  }

node

route.post('/image', (req, res, next) => {//上传头像

  var form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, '../../test/img/'); //图片存储的路径
  form.maxFieldsSize = 1 * 1024 * 1024; //用户头像大小限制为最大1M    
  form.keepExtensions = true; //使用文件的原扩展名  
  form.parse(req, function (err, fields, file) {
    var filePath = '';
    let userName = fields.userName
    let oldUrl = fields.domImg.replace("http://localhost/img/",'')//图片存储的路径,我存放在服务器的img文件夹里,跟上面路径对应
    console.log(userName)
    console.log(oldUrl)
    
    if (file.tmpFile) {
      filePath = file.tmpFile.path;
    } else {
      for (var key in file) {
        if (file[key].path && filePath === '') {
          filePath = file[key].path;
          var url = filePath;
        var index = url.lastIndexOf("\\");
        loadPath = url.substring(index + 1,url.length);//只取最后一个\后面的内容
          console.log(loadPath)
          console.log(filePath)
           const changeImg = `UPDATE users SET img = '${loadPath}' WHERE userName = '${userName}'`
                    db.query(changeImg,(err,data)=>{//存入数据库
                        console.log(data)
                         if(err){
                            res.send({"msg":"服务器错误","code":500}).end();
                        }else{
                            console.log("../../Desktop/test/img/"+oldUrl)

//避免频繁更新头像导致服务器图片过多,上传新的图片成功后删除旧的图片                            fs.unlink("../../Desktop/test/img/"+oldUrl,function(error){//删除原图像
                                if(error){
                                    console.log(error);
                                    return false;
                                }
                                console.log('删除原头像成功');
                            })
                            res.send({"code":200,"msg":"上传成功"}).end();
                        }
                    })
          // res.send("文件上传成功")
          break;
        }
      }
    }
  });
})

上传图片后,图片存在服务器img文件夹里面:在这里插入图片描述
图片
在这里插入图片描述

发布了43 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/darkCloudss/article/details/103925362