vue el-element-ui upload图片上传

项目中使用图片上传功能,要实现可以原地上传和修改,一直查找许多资料,结合资料和组件完成此功能,希望对后边的人有帮助

源码:

     style部分

           <el-upload
              action="#"
              list-type="picture-card"
              :limit="6"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeImageUpload"
              :http-request="uploadImage"
              :auto-upload="true"
            >
              <i class="el-icon-plus"></i>
           </el-upload>
           <el-dialog :visible.sync="dialogVisible">
             <img width="100%" :src="dialogImageUrl" alt />
           </el-dialog>
    javaScript部分
      
        export default {
              data(){
                return {
                   dialogImageUrl: '' ",
                  dialogVisible: false,
                  fileList: [],
                       }
                  },
            methods{
    //图片上传之前
    beforeImageUpload(file) {
      console.log(file)
      var testmsg=file.name.substring(file.name.lastIndexOf('.')+1) 
      const isJpg = testmsg === 'jpg' || testmsg === 'png'
      if (!isJpg) {
        this.$message.error('上传图片只能是 jpg 或 png 格式!')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      // return false // (返回false不会自动上传)
    },
handlePictureCardPreview(file) {
     this.dialogImageUrl = file.url
     this.dialogVisible = true
  },
handleRemove(file, fileList) {
      for(var i = 0; i < this.fileList.length; i++){
        if(this.fileList[i].url === file.url){
          deleteImageReport(this.fileList[i].id).then(res =>{
            this.$message.success('删除图片成功')
          })
          this.fileList.splice(i, 1)
        }
      }
    },
//上传图片
    uploadImage(image){
      console.log(image.file)
      let report = this.currentUser.id
      let params = new FormData()
      params.append('image', image.file)
      params.append('report', report)
      uploadImageFiles(params).then(res => {
        console.log(res)
        let url = { url: res.data.image, id:res.data.id }
        this.fileList.push(url)
        this.$message.success('上传成功')
      }).catch(() =>{
        this.$message('上传失败,请重新上传')
      })
    },
            }
    }
 

猜你喜欢

转载自www.cnblogs.com/guoshuai2019/p/12215326.html