• vue中使用axios post上传头像/图片并实时显示到页面


    在前端开发中,为了更好的用户体验,在头像上传时会先将图片显示到页面然后点击保存按钮 完成图片的上传成功 代码部分有参考他人的写法。

    html代码:

    1.  
      <div id="myPhoto" v-show="personalPhoto">
    2.  
      <div class="viewPhoto">
    3.  
      <img src="" alt="" id="portrait"style=" 300px;height: 300px" />
    4.  
      </div>
    5.  
      <div class="listBox">
    6.  
      <dl>
    7.  
      <dt>请上传图片</dt>
    8.  
      <dd>
    9.  
      <input type="file"id="saveImage" name="myphoto" >
    10.  
      </dd>
    11.  
      </dl>
    12.  
      </div>
    13.  
      <div class="save">
    14.  
      <input type="button" value="保存图片" @click="imageSubmit">
    15.  
      </div>
    16.  
      </div>

    js代码:

    1.  
      //实时显示该图片在页面
    2.  
       great(){
    3.  
      document.getElementById('saveImage').onchange = function () {
    4.  
      var imgFile = this.files[0];
    5.  
      var fr = new FileReader();
    6.  
      fr.onload = function () {
    7.  
      document.getElementById('portrait').src = fr.result;
    8.  
      };
    9.  
      fr.readAsDataURL(imgFile);
    10.  
      }
    11.  
      },

    js代码部分说明:因为是在vue的methods方法中申明的函数,所以还需要在mounted 方法中使用this.great()挂载该方法。

    图片上传部分的js代码:

    1.  
      imageSubmit(){
    2.  
      let x = document.getElementById('saveImage').files[0];
    3.  
      console.log(x);
    4.  
      let params = new FormData() ; //创建一个form对象
    5.  
      params.append('file',x,x.name); //append 向form表单添加数据
    6.  
      //添加请求头 通过form添加的图片和文件的格式必须是multipart/form-data
    7.  
      let config = {
    8.  
      headers:{'Content-Type':'multipart/form-data'}
    9.  
      };
    10.  
      this.$axios.post("/user/image",params,config)
    11.  
      .then(function(res){
    12.  
      console.log(res);
    13.  
      this.imageSave = res.data.image;
    14.  
      sessionStorage.setItem('headImg',this.imageSave); //将图片保存,并能够在其他地方加载显示
    15.  
      router.go(0); //刷新页面,头像改变
    16.  
      }.bind(this))
    17.  
      .catch(function (error) {
    18.  
      console.log(error);
    19.  
      })
    20.  
      }
    21.  
      },

    最终效果图:

    注:在后来的开发过程中发现,上传图片在上传服务器前在页面加载可以使用

    var windowURL = window.URL || window.webkitURL;
  • 相关阅读:
    springboot开启事务控制
    数据库的四种特性
    springboot之事务
    整合springboot+mybatis+mysql之增删改查(三)
    整合springboot+mysql+mybatis之控制台打印sql(二)
    整合springboot+mysql+mybatis之新增(一)
    解决springboot的依赖包中jar是灰色的问题
    springboot引擎模板之thymeleaf官网学习(四)
    springboot模板引擎之模板整合之thymeleaf(三)
    springboot模板引擎之模板整合之freemarker(二)
  • 原文地址:https://www.cnblogs.com/xiaocaiyuxiaoniao/p/9437036.html
Copyright © 2020-2023  润新知