vue中图片的上传、查看组件

1、上传 

<template>
  <div class="uploadImgBody">
    <div v-for="(item,index) in UploadList"
         class="imgList"
         :key="'img'+index"
         @mouseover="mouseover(item)"
         @mouseout="mouseout(item)">
      <div class="deleteImg"
           v-show="item.delete"
           title="移除"
           @click="removeImg(index,item)">
        <Icon type="md-close" />
      </div>
      <viewer class="viewer"
              :images="[item.src]">
        <img :src="item.src"
             class="imgBlock" />
      </viewer>
    </div>
    <Icon type="ios-camera"
          class="uploadImg"
          size="20"
          @click="chooseFile"></Icon>
    <input type="file"
           v-show="false"
           ref="filElem"
           multiple
           value=""
           accept="image/png"
           @change="preview" />
  </div>
</template>
<script>
export default {
  data () {
    return {
      lastImgIndex: 0,
      UploadList: []
    }
  },
  mounted () { },
  methods: {
    //实现将项目的图片转化成base64
    convertImgToBase64 (url, callback, outputFormat) {
      var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
    },
    dataURItoBlob (dataURI) {
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
      var byteString = atob(dataURI.split(',')[1]); //base64 解码
      var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
      var intArray = new Uint8Array(arrayBuffer); //创建视图

      for (var i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i);
      }
      return new Blob([intArray], { type: mimeString });
    },
    //将base64转换为文件
    dataURLtoFile (dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime
      });
    },
    //插入待上传队列 imgArray 为 图片链接与名称的集合 [{name:"",src:""}]
    addFileQuery (imgArray) {
      let that = this;
      let baseURL = that.axios.defaults.baseURL;
      if (imgArray.length > 0) {
        for (let i = 0; i < imgArray.length; i++) {
          let _img = imgArray[i];
          let _name = _img.name;
          let _src = _img.src;
          if (_src.indexOf("http") == -1) {
            _src = baseURL + "/" + _src;
          }
          that.convertImgToBase64(_src, function (base64Img) {
            let imgBlod = that.dataURItoBlob(base64Img);
            let file = new window.File([imgBlod], _name, { type: imgBlod.type })
            let _map = {
              src: _src,//图片地址
              name: _name,//图片名称
              file,
              delete: false
            }
            that.UploadList.push(_map);
          });
        }
      }
    },
    //清空
    clearUpload () {
      this.$refs.filElem.value = "";
      this.UploadList = [];
    },
    removeImg (index, item) {
      this.UploadList.splice(index, 1);
      // console.log(this.$refs.filElem.value);
    },
    mouseover (obj) {
      obj.delete = true;
    },
    mouseout (obj) {
      obj.delete = false;
    },
    chooseFile () {
      this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
    },
    preview (elm) {
      let that = this;
      const files = elm.target.files;
      if (files) {
        for (let i = 0; i < files.length; i++) {
          let file = files[i];
          if (file.size > 1024 * 1024 * 3) {
            this.$Message.error("文件大小不能超过3M")
          } else {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (item) {
              let _map = {
                src: item.target.result,//图片地址
                name: file.name,//图片名称
                file,
                delete: false
              }
              that.UploadList.push(_map);
            };
          }
        }
      }
    },
    //提交
    uploadFile () {
      console.log("进uploadFile")
      let that = this;
      let UploadList = that.UploadList;
      console.log(UploadList)
      let formData = new FormData();
      UploadList.forEach((e, i) => {
        formData.append("files" + i, e.file);
      })
      let files = formData.get("files0")
      console.log(files)
      let headers = {
        'Content-Type': 'multipart/form-data'
      }
      this.axios.post("/api/File/UploadFile/", formData, { headers: headers }).then(res => {
        console.log(res)
      })
    }
  }
}
</script>
<style scoped>
.viewer {
  display: flex;
}
.uploadImgBody {
  width: 100%;
  display: flex;
}
.imgBlock {
  height: 70px;
  margin-right: 10px;
}
.imgList {
  width: 70px;
  height: 70px;
  margin-right: 10px;
  position: relative;
  overflow: hidden;
}
.deleteImg {
  position: absolute;
  top: 0;
  right: 0;
  background: radial-gradient(circle, #f8f8f9, #19be6bdb, #19be6b);
  border-radius: 23px;
  color: #ffffff;
  font-size: 12px;
  width: 15px;
  height: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.uploadImg {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dashed #dddddd;
  cursor: pointer;
}
</style>
//1、引入组件
 import UploadImg from '@/components/UploadFile/uploadImg'
//2、使用组件
 <UploadImg ref="UploadImg" />

2、查看

<template>
  <div>
    <viewer class="viewer"
            :images="itemData">
      <img v-for="(item,index) in itemData"
           :src="item.indexOf('http:')==-1?urlTou+item:item"
           :key="index"
           :onerror="'this.src=\''+errorImg+'\''" />
    </viewer>
  </div>
</template>
<script>
export default {
  data () {
    return {     
      urlTou: "",
      errorImg: require("@/assets/Icon/errorImg.png"),
      itemUrl: '',
      modal11: false     
    };
  },
  props: {
    // 子元素数据
    itemData: {
      type: Array,
      default () {
        return []
      }
    }
    
  },
  watch: {
    itemData: {
      handler (val, oldVal) {
        console.log(val)
      },
      deep: true
    }
  },
  mounted () {
    let baseURL = this.axios.defaults.baseURL
    this.urlTou = baseURL.substring(0, baseURL.length - 1)
  },
  methods: {
    show (item) {
      this.modal11 = true
      this.itemUrl = this.urlTou + item
    },
    remove () {
      this.modal11 = false
    }
  },
};
</script>
<style scoped>
.viewer {
  display: flex;
  flex-wrap: wrap;
  /* padding: 0 1rem; */
  background-color: #fff;
}
.viewer > img {
  width: 72px;
  height: 48px;
  margin: 2px 0;
}
.imgbox {
  background-color: rgba(0, 0, 0, 0.6) !important;
  padding: 0;
}
.img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
}
.img > img {
  position: absolute;
  width: 100%;
  top: 50%;
  transform: translateY(-50%);
}
</style>
//1、引入组件
import ViewImg from '@/components/Viewer/ViewerB'
//2、使用组件
 <ViewImg :itemData="Delimgs">
 </ViewImg>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值