使用element+vue+node实现完整的头像上传预览功能

html部分

<div style="display: inline-block;vertical-align: middle;margin-top: 15px">
              <!--头像上传-->
              <el-upload
                class="upload-demo"
                drag
                ref="upload"
                :action="imgUrl"
                :auto-upload="false"
                :onChange="handlePreview"
                :on-preview="handlePreview2"
                :on-remove="handleRemove"
                list-type="picture"
                name="imgfile"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
              </el-upload>
            </div>

在这里插入图片描述

//文件上传服务器文件夹
      submit(id){
        if (this.$refs.upload.uploadFiles.length > 1) {
          this.$message.error('只能上传一张头像');
          this.dialogFormVisible = true;
        } else if (this.$refs.upload.uploadFiles.length == 1) {
          console.log(this.inputValue.name);
          //提交form表单
          this.$refs.upload.submit();
          this.dialogFormVisible = false;
          let a = new Promise((resolve, reject) => {
            resolve(id)
          });

          let b = new Promise((resolve, reject) => {
            //上传后根据ID修改图片路径并返回文件名称,在这里需要延迟是因为无法和数据库同时同步操作
            setTimeout(() => {
              this.axios.get('http://localhost:3000/imagesUpdate?id=' + id).then((data) => {
                for (let i = 0; i < this.tableData.length; i++) {
                  if (this.tableData[i]._id == id) {
                    this.tableData[i].headPicture = 'http://localhost:3000/images/' + data.data;
                    console.log(this.tableData[i].headPicture);
                  }
                }
              });
            }, 300);
            resolve('success');
          });

          a.then((data) => {
            return b;
          }).catch((err) => {
            console.log(err);
          }).then((data) => {
            setTimeout(() => {
              //清空上传文件的暂存区
              this.$refs.upload.clearFiles();
            }, 500);
          })
        } else {
          this.$message.error('你没有选择头像');
          this.dialogFormVisible = false;
        }
      },
      //监听图片上传状态,用于回显
      handlePreview(file) {
        console.log(file.name);
        //图片验证,不是JPG/PNG格式则将该图片从this.$refs内的数组中删除
        for (let i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
          if (this.$refs.upload.uploadFiles[i].name.indexOf('jpg') != -1 || this.$refs.upload.uploadFiles[i].name.indexOf('png') != -1) {
            this.$message.success('上传成功');
            //将该图片的url作为路径图片回显
            document.querySelector('#img-demo').src = file.url;
          } else {
            this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
            //非法格式则删除
            this.$refs.upload.uploadFiles.splice(i, 1);
          }
        }
      },
      //动态展出上传的图片,实现点击切换
      handlePreview2(file){
        //element内置的方法,点击图片时获取url实时回显
        document.querySelector('#img-demo').src = file.url;
      },

在这里插入图片描述

值得注意的是,element的API中默认提供的方法有一个坑
就是你在上传一个图片之后,继续点击上传时,它的暂存区里已经存在一张图片,导致你每次上传的头像再更新时永远都是前几次上传过的头像

所以在这个时候我们需要将element内置的暂存区清除this.$refs.upload.clearFiles();

后台部分

//上传文件
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images');
    },

    /*以时间戳命名的文件*/
    filename: function (req, file, cb) {
        cb(null, `${Date.now()}-${file.originalname}`)
    }

    /*filename: function (req, file, cb) {
        cb(null, `${file.originalname}`)
    }*/
});
let upload = multer({storage: storage});
let imageName = '';
app.all('/images', upload.array('imgfile', 40), (req, res, next)=> {
    let files = req.files;
    if (!files[0]) {
        res.send('error');
        //在此地加上return 纯属于防止express报错,因为send和end结束之后都会调用return
        return 'error'
    } else {
        console.log(files[0].filename);
        imageName=files[0].filename;
        res.send('success');
        return 'success'
    }
});

//需改用户头像路径
app.all('/imagesUpdate',(req,res,next)=>{
    let id = req.query.id;
    //将传来的ID转换为mongodb的ObjectId,需要引入mogoose
    let _id = mongoose.Types.ObjectId(id);
    console.log(id);
    user.update({"_id":_id},{$set:{headPicture:'http://localhost:3000/images/'+imageName}},{upsert:true,multi:false},(err,data)=>{
        console.log(imageName,'&&&&&&&&&&&&&&&&&&&&&&&&&');
        res.send(imageName);
    });
});

猜你喜欢

转载自blog.csdn.net/qq_42427109/article/details/84975401
今日推荐