vue-js-上传图片

用的formData的方法上传
效果图

<div class="per-infos-box infos-head">
   <p class="infos-title">头像</p>
   <img :src="imageUrl" class="avatar" alt />
   <input type="file" @change="getFile($event)" />
 </div>
 data() {
    
    
    return {
    
    
      userInfo: {
    
    },
      imageUrl: ""
    };
  },
  mounted() {
    
    
    this.getUserInfo();//获取全部个人信息
  },
  methods: {
    
    
//获取上传图片
    getFile(event) {
    
    
      let file = event.target.files[0];
      //获取上传元素信息
      var that = this;
      event.preventDefault();
      // 只能通过formData方式来传输文件
      var formData = new FormData();
      formData.append("file", file);
      let config = {
    
    
        headers: {
    
    
          "Content-Type": "multipart/form-data"
        }
      };
      console.log(file, formData, config);
      //"http://120.26.243.175:82/images/savePhoto"后端给的上传图片接口
      this.$http
        .post("http://120.26.243.175:82/images/savePhoto", formData, config)
        .then(function(res) {
    
    
          // console.log(res.data);
          if (res.data.result == 0) {
    
    
            /*这里做修改请求*/
            console.log(111);
            changeInfosApi({
    
    //修改头像的接口,传的参是刚才返回的图片URL
              icon: res.data.data
            }).then(res => {
    
    
              if (res.data.result != 0) {
    
    
                Toast(res.data.msg);
              } else {
    
    
                Toast("修改成功");
                that.getUserInfo();//更新数据
              }
            });
          }
        });
    },

这里是部分样式
这是样式

猜你喜欢

转载自blog.csdn.net/yxgd_1442962728/article/details/105411851