vue ajax上传图片

(vue ajax上传图片)

最近在做一个手机端H5页面,需要做图片上传功能,就简单的做一个demo,后端使用的是thinkPHP5,代码此次省略,
下面贴上前端代码,
HTML 代码部分:

<input type="file" id="fileinp" accept="image/*" ref="avatarInput" @change="update" />
<br>
	<img :src="avatar" style="display:block;width:35%;margin:20px auto ;border:1px solid #ccc;padding:10px" alt="照片展示区"><br>
<button @click="uploadbtn" >上传</button>

javascript代码部分:

var vapp = new Vue({
  el : '#app',
  data : {
    avatar:"",
    imgname:'',
  },
  created : function(){
  },
  methods : {
    update:function(e){
      let that = this
      let file = e.target.files[0];
      let imgsize = file.size;
      if(imgsize > 5242880){
        alert("图片大小不能超过5M"); return false;
      } 
    },
    uploadbtn:function(){
      let that = this
      let files = this.$refs.avatarInput.files[0];
      let param = new FormData(); //创建form对象 
       param.append('file',files);//通过append向form对象添加数据 
     $.ajax({
        url:'http://localhost/index.php/index/index/uploadimg',
        type:'post',
        data:param,
        dataType:'json',
        processData: false,
        contentType:false,
        success:function(res){
          console.log(res)
          that.avatar="http://localhost"+res.src; 
        },
        error:function(err){
          console.log(err)
        }
      })
    }
  }
  
});

有做的不好的地方,还请多多包涵

猜你喜欢

转载自blog.csdn.net/renyi2013/article/details/88846302