当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue 使用原生组件上传图片的实例

vue 使用原生组件上传图片的实例

2020年09月09日  | 移动技术网IT编程  | 我要评论
需求描述:需要将后台返回的图片路径赋值到img的 src1 一个页面上传一张图片当一个页面只有一个位置需要上传图片,很简单,直接绑定上传按钮html页面 <div class="col-md-4

需求描述:需要将后台返回的图片路径赋值到img的 src

1 一个页面上传一张图片

当一个页面只有一个位置需要上传图片,很简单,直接绑定上传按钮

html页面

 <div class="col-md-4">
  <input class="hidden" accept="image/png,image/jpg" type="file" id="tempuploadfile" v-on:change="uploadpic($event)" />
  <input class="hidden" v-model="mapitem.mapicon" />
  <img class="imgbgbox" v-bind:src="mapitem.mapicon" />
 </div>

js代码:封装上传图片的方法

 uploadpic(e) {
  var _self = this;
  var inputfile = e.target;
  if (!inputfile.files || inputfile.files.length <= 0) {
   return;
  }
  var file = inputfile.files[0];
  var formdata = new formdata();
  formdata.append('file', file);
  formdata.append('savedir', 'map/mapitem');
  formdata.append("filename", $.whiskey.tools.dateformat(new date(), "hhmmssffff"));
  $.ajax({
   url: "/upload/uploadpic",//后台上传图片的方法
   type: 'post',
   datetype: 'json',
   cache: false,
   data: formdata,
   processdata: false,
   contenttype: false,
   success: function (res) {
    if (res.resulttype == 3) {
     var filepath = res.data.file;//后台返回的图片路径
     _self.mapitem.mapicon = filepath;//将路径赋值到声明的变量中
    }
   }
  });
},

2 一个页面上传多张图片

当一个页面有多个位置需要上传图片,如果按照上面方法,得需要绑定多个上传函数,所以我把重复的部分封装出来,用到了函数

html页面

 <div class="col-md-4">
  <input class="hidden" accept="image/png,image/jpg" type="file" id="tempuploadfile" v-on:change="uploadpic($event)" />
  <input class="hidden" v-model="mapitem.mapicon" />
  <img class="imgbgbox" v-bind:src="mapitem.mapicon" />
 </div>

js代码:封装上传图片的方法

 uploadpic(e) {
  var _self = this;
  var inputfile = e.target;
  _self.uploadimg(inputfile).then(data => {
   _self.mapitem.mapicon = data;//data为取到的图片路径
  })
},
//封装函数
 uploadimg(inputfile) {
  var _self = this;
  if (!inputfile.files || inputfile.files.length <= 0) {
   return;
  } 
  return new promise((suc,err)=>{
   var file = inputfile.files[0];
   var filepath = "";
   var formdata = new formdata();
   formdata.append('file', file);
   formdata.append('savedir', 'map/mapsite');
   formdata.append("filename", $.whiskey.tools.dateformat(new date(), "hhmmssffff"));
   $.ajax({
    url: "/upload/uploadpic",
    type: 'post',
    datetype: 'json',
    cache: false,
    data: formdata,
    processdata: false,
    async:false,
    contenttype: false,
    success: function (res) {
     if (res.resulttype == 3) {
      filepath = res.data.file;
      suc(filepath);
     }
    }
   });
  })
 },
},

补充知识:vue 利用原生input上传图片并预览并删除

看代码~

<template>
 <div class="com-upload-img">
 <div class="img_group">
  <div v-if="allowaddimg" class="img_box">
  <input type="file" accept="image/*" multiple="multiple" @change="changeimg($event)">
  <div class="filter" />
  </div>
  <div v-for="(item,index) in imgarr" :key="index" class="img_box">
  <div class="img_show_box">
   <img :src="item" alt="">
   <i class="img_delete" @click="deleteimg(index)" />
   <!-- <i class="img_delete" @click="imgarr.splice(index,1)"></i> -->
  </div>
  </div>
 </div>
 </div>
</template>

js部分

<script>
export default {
 name: 'comupload',
 data() {
 return {
  imgdata: '',
  imgarr: [],
  imgsrc: '',
  allowaddimg: true
 }
 },
 methods: {
 changeimg: function(e) {
  var _this = this
  var imglimit = 1024
  var files = e.target.files
  var image = new image()
  if (files.length > 0) {
  var dd = 0
  var timer = setinterval(function() {
   if (files.item(dd).type !== 'image/png' && files.item(dd).type !== 'image/jpeg' && files.item(dd).type !== 'image/gif') {
   return false
   }
   if (files.item(dd).size > imglimit * 102400) {
   // to do sth
   } else {
   image.src = window.url.createobjecturl(files.item(dd))
   image.onload = function() {
    // 默认按比例压缩
    var w = image.width
    var h = image.height
    var scale = w / h
    w = 200
    h = w / scale
    // 默认图片质量为0.7,quality值越小,所绘制出的图像越模糊
    var quality = 0.7
    // 生成canvas
    var canvas = document.createelement('canvas')
    var ctx = canvas.getcontext('2d')
    // 创建属性节点
    var anw = document.createattribute('width')
    anw.nodevalue = w
    var anh = document.createattribute('height')
    anh.nodevalue = h
    canvas.setattributenode(anw)
    canvas.setattributenode(anh)
    ctx.drawimage(image, 0, 0, w, h)
    var ext = image.src.substring(image.src.lastindexof('.') + 1).tolowercase()// 图片格式
    var base64 = canvas.todataurl('image/' + ext, quality)
    // 回调函数返回base64的值
    if (_this.imgarr.length <= 4) {
    _this.imgarr.unshift('')
    _this.imgarr.splice(0, 1, base64)// 替换数组数据的方法,此处不能使用:this.imgarr[index] = url;
    if (_this.imgarr.length >= 5) {
     _this.allowaddimg = false
    }
    }
   }
   }
   if (dd < files.length - 1) {
   dd++
   } else {
   clearinterval(timer)
   }
  }, 1000)
  }
 },
 deleteimg: function(index) {
  this.imgarr.splice(index, 1)
  if (this.imgarr.length < 5) {
  this.allowaddimg = true
  }
 }
 }
}
</script>

以上这篇vue 使用原生组件上传图片的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网