vue+elementUI上传图片单张/多张至七牛云,组件代码

1.效果

在这里插入图片描述

2.在components中创建UploadImg目录,再创建uploadImg.vue文件

在这里插入图片描述

3.安装引入七牛云

// 下载qiniu-js
npm install qiniu-js

// 在页面中引入
import * as qiniu from 'qiniu-js'


4.代码

<template>
  <div class="warpImgBox">
    <div
      class="img-list-item common mb_10"
      v-for="(item, index) in fileList"
      :key="index"
    >
      <!-- <video
        v-if="!matchType(item.name)"
        :style="{ width: w, height: h, margin: '0 9px' }"
        controls="controls"
        :src="item.url"
      >
        您的浏览器不支持视频播放
      </video> -->
      <el-image
        @mouseover="srcList = [item]"
        :preview-src-list="srcList"
        :style="{ width: w, height: h, margin: '0 9px' }"
        :src="item"
        fit="cover"
      ></el-image>
      <i class="del-img" @click="forkImage(index)" v-if="isShowImg == true"></i>
    </div>
    <div v-if="maxlength < limit" @click="change">
      <el-upload
        action=""
        :data="dataObj"
        :show-file-list="false"
        :auto-upload="true"
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload"
        :on-progress="uploadVideoProcess"
        :http-request="FileForQiNiu"
      >
        <span
          class="warpss"
          :style="{ width: w, height: h, lineHeight: h }"
          v-if="isShowImg == true"
        >
          <i
            class="el-icon-plus"
            :style="{
              color: '#8C939D',
              fontSize: '18px',
              fontWeight: 'bold',
              padding: paddings,
            }"
          ></i>
        </span>
      </el-upload>
    </div>
  </div>
</template>
<script>
import { GetqiniuToken } from "@/api/article";//获取七牛云token的接口,一般是后端提供接口获取
import * as qiniu from "qiniu-js";//引入七牛云
export default {
  name: "uploadImg",
  props: {
    //是否需要上传图片(false:需要,true:不需要,只能查看图片不能做任何操作)
    isShowImg: {
      type: Boolean,
      default: false,
    },
    //个数显示
    limit: {
      type: Number,
      default: 5,
    },
    maxlength: {
      type: Number,
    },
    value: Array,
    //最大上传图片数量
    maxCount: {
      type: Number,
      default: 5,
    },
    //宽度
    w: {
      type: String,
      // default:'100px'
    },
    //高度
    h: {
      type: String,
      // default:'100px'
    },
    paddings: {
      type: String,
    },
  },
  data: function () {
    return {
      srcList: [],
      videoFlag: false,
      isShow: true,
      videoUploadPercent: 0,
      count: 5,
      videis: false,
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
      dialogVisible: false,
      dialogImageUrl: [],
    };
  },
  computed: {
    fileList() {
      this.$emit("videoData", this.value);
      return this.value;
    },
  },
  mounted() {
    if (this.fileList.length < this.limit) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  },
  methods: {
    //图片视频匹配
    matchType(name) {
      //后缀获取
      let suffic = "";
      //获取类型结果
      let result = "";
      try {
        let fileArr = name.split(".");
        suffic = fileArr[fileArr.length - 1];
        // console.log('suffic',suffic);
      } catch (error) {
        suffic = "";
      }
      //图片格式
      var imgList = ["png", "jpg", "jpeg", "bmp", "gif"];
      //进行图片匹配
      result = imgList.some((item) => {
        return item === suffic;
      });
      // console.log('结果',result);
      if (result) {
        result = "image";
        // console.log('结果',result);
        return result;
      }
    },
    //删除视频/图片
    forkImage(index) {
      var data = this.fileList.splice(index, 1);
      this.$emit("delFile", this.fileList);
      if (this.fileList.length < this.limit) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    change() {
      if (this.fileList.length < this.limit) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    getUUID() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
        return (
          c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8"
        ).toString(16);
      });
    },
    emitInput(fileList) {
      let value = [];
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i]);
      }
      this.$emit("input", value);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    //上传图片/视频成功后的操作
    handleUploadSuccess(res, file) {
      let url =
        this.dataObj.host +
        "/" +
        this.dataObj.key.replace("${filename}", file.name);
      this.fileList.push(url);
      this.emitInput(this.fileList);
      this.dialogVisible = true;
      this.videoUploadPercent = 0;
      if (this.fileList.length < this.limit) {
        this.isShow = true;
      } else {
        this.isShow = false;
        this.$message({
          message: "最多只能上传" + this.limit + "个视频/张图片",
          type: "warning",
          duration: 1000,
        });
      }
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoUploadPercent = Math.floor(event.percent);
    },
    beforeUpload(file) {
      // this.videoFlag = true;
      //视频/图片校验
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "image/jpeg",
          "image/PNG",
          "image/gif",
          "image/png",
        ].indexOf(file.type) == -1
      ) {
        this.$message.error("请上传正确的视频/图片格式");
        return false;
      }
    },
    // 获取七牛云token
    FileForQiNiu(param) {
      console.log("普通上传需要的参数", param);
      let that = this;
      //获取七牛云token的接口
      GetqiniuToken().then((response) => {
        const key =
          "cy_magic/" +
          new Date().getTime() +
          "_" +
          param.file.size +
          param.file.name;
        const putExtra = {};
        const config = { useCdnDomain: true };
        // file:图片数据;key:图片名称;token:服务端获取的token;putExtra:额外的参数;config:其他配置
        const observable = qiniu.upload(
          param.file,
          key,
          response.token,
          putExtra,
          config
        );
        const error = function (err) {};

        const complete = function (res) {
          const fn = param.file.name;
          const fu_r = res.key; // 相对路径
          const fu_Url = "拼接地址比如:https://www.sss.com/" + res.key; // 绝对路径
          that.fileList.push(fu_Url);
          that.emitInput(that.fileList);
          const type = param.data.type; //根据type 区分上传的是哪个分类
        };
        const next = function (response) {
          param.onProgress({ percent: response.total.percent });
        };
        const x = observable.subscribe(next, error, complete);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.warpss {
  display: inline-block;
  border: 1px dashed #dee5ed;
}

::v-deep.el-upload-list {
  display: none;
}

.el-upload-video {
  width: 149px;
  height: 149px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload-video-i {
  font-size: 20px;
  font-weight: bold;
  padding-top: 43px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

//视频
.img-list-item {
  position: relative;
}

.img-list-item i.del-img {
  width: 20px;
  height: 20px;
  display: inline-block;
  background: rgba(0, 0, 0, 0.6);
  background-image: url(../../assets/images/close.png);//关闭按钮图片,我会放在末尾
  background-size: 18px;
  background-repeat: no-repeat;
  background-position: 50%;
  position: absolute;
  top: 0;
  right: 9px;
}
.warpImgBox {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  align-content: flex-start;
}
</style>

//关闭按钮
在这里插入图片描述

5.页面使用组件

<template>
<div>
<upload-img
            @videoData="getDataInput"
            :isShowImg="isShowImg"
            :maxlength="slider_image.length"
            :limit="limit"
            w="150px"
            h="150px"
            v-model="slider_image"
          ></upload-img>
</div>
</template>
<script>
import uploadImg from "@/components/UploadImg/uploadImg.vue";//引入组件
export default {
  name: "111",
  components: { uploadImg },
  data() {
    return {
    limit:2,//图片限制张数
    isShowImg: true,//组件是否可上传
    slider_image:[],//图片数组
    formInline:{
    icon:""
    }
    }
    },
    methods:{
      //获取子组件数据
    getDataInput(e) {
      this.formInline.icon = "";
      this.slider_image = e;
      if (e.length > 0) {
        this.formInline.icon = e[0];
      }
    },}}
</script>
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值