封装 图片下载组件

图片

this.minio 全局封装的变量 => 文件外发地址

调用

  <moreImageUploadVue
                    :limit="1"
                    :file-list="editForm.fileList"
                    :titleText="titleText"
                    :disabled="true"
                  >
 </moreImageUploadVue>
// 如果想 只读  加 :titleText="titleText"   titleText='查看'

代码封装

<template>
  <div class="uploadImgBOx">
<el-upload
      action="#"
      ref="uploadlogo"
      :before-upload="beforeUpload"
      :http-request="uploadFile"
      :on-success="upSuccess"
      :on-change="upChange"
      :on-error="upError"
      :on-progress="handlePreview"
      :file-list="fileList"
      :class="titleText === '查看' || titleText === '详情' ? 'ck' : ''"
      list-type="picture-card"
    >
	<i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="scope">
        <!-- {{ process }} -->
        <!--   -->
        <img
          class="el-upload-list__item-thumbnail"
          :src='mySrc(scope.file.url)'
           alt=""
        />
		<span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(scope.file)"
          >
            <i class="el-icon-zoom-in"></i>
             </span>
          <span
		  <span  v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(scope.file)">
            <i class="el-icon-download"></i>
          </span>

		 <span v-if="!disabled && titleText !== '查看' && titleText !== '详情'"
            class="el-upload-list__item-delete"
            @click="handleRemove(scope.file)" >
            <i class="el-icon-delete"></i>
          </span>
          </span>
      </div>
      <div  slot="tip"
        v-if="titleText !== '查看' && titleText !== '详情'"
        class="el-upload__tip"
 >
        仅支持jpg、jpeg、png格式,且文件需小于10MB。
      </div>
    </el-upload>
<el-dialog title="图片详情" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
 </div>
</template>
<script>
import { uploadFilesAPI } from "@/api/serviceLaw.js"
export default {
 props: {
    fileList: { type: Array, default: null },
    titleText: { type: String, default: "" },
    flogSingle: {
      type: Boolean,
 default: false
    }
  },
  data () {
    return {
      editForm: {
        fileUrl: ""
      },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false
    }
  },
   mounted () {
    console.log(this.fileList, this.flogSingle, "this.fileListmmmmm")
    // 如果有内容
    // if (this.fileList.length > 0) {
    //   this.fileList = this.fileList[0].url
    // }
  },
  methods: {
    mySrc(url){
    let str=(url.indexOf('b') === -1?this.minio + url : url)
      return str
    },
    handlePreview (file, fileList) {
      console.log(file, fileList)
    },
    //上传的文件改变时(覆盖原来的文件)
upChange (file, fileList) {
      if (!this.flogSingle) return
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
    },
     // 上传失败
    upError () {
      this.editForm = {
        fileUrl: ""
      }
      this.$emit("sunceessReulst", this.fileList, this.editForm)
      this.domUpload.style.zIndex = -1
      this.$message({
        type: "error",
        message: "上传失败",
        showClose: true,
        offset: 80
  })
    },
    //上传之前
     beforeUpload (file) {
      console.log("zzzzxxx")
      console.log(file, "filess")
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1)
      const whiteList = ["jpg", "jpeg", "png"]
      console.log(
        this.editForm,
        this.dialogImageUrl,
        "dialogImageUrl,editForm"
      )
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message({
          type: "error",
          message: "上传文件只能是 jpg,jpeg,png 格式",
          showClose: true,
          offset: 80
        })
        this.fileList = []
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message({
          type: "error",
           message: "上传文件不能超过10MB",
          showClose: true,
          offset: 80
        })
        this.fileList = []
        return false
      }
    },
     // 上传成功
    upSuccess (response, file, fileList) {
      // this.$emit("successDataBalc", this.editForm)
      this.$message({
        type: "success",
         message: "上传成功",
        showClose: true,
        offset: 80
      })
      // 设置url
      if (!this.flogSingle) {
        this.fileList.push(file)
      }
      this.$emit("sunceessReulst", this.fileList, this.editForm)
    },
    cloneObj (obj) {
      var newObj = {}
      if (obj instanceof Array) {
        newObj = []
      }
      for (var key in obj) {
        var val = obj[key]
        newObj[key] = typeof val === "object" ? this.cloneObj(val) : val
      }
      return newObj
    },
    /**
     * 移除图片
     * @param {*} file
     */
     async handleRemove (file) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
         confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => err)
      if (result === "cancel") return
      let uploadFiles = this.$refs.uploadlogo.uploadFiles
      let unmIndex = undefined
      this.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          unmIndex = index
          return
        }
      })
      console.log(unmIndex, 'unmIndex')
      this.$nextTick(() => {
        this.fileList.splice(unmIndex, 1)
        uploadFiles.splice(unmIndex, 1)
        console.log(this.fileList, 'this.fileList')
        this.$emit("sunceessReulst", this.fileList, this.editForm)
      })
},
/**
     * 放大图片
     * @param {*} file
     */   
      handlePictureCardPreview (file) {
      console.log(file)
      this.dialogImageUrl =
        file.url.indexOf("b") === 0 ? file.url : this.minio + file.url

      this.dialogVisible = true
    },     
    /**
     * 图片下载
     * @param {*} file 文件
     */
     handleDownload (file) {
      let image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous")
      image.onload = function () {
        let canvas = document.createElement("canvas")
        canvas.width = image.width
        canvas.height = image.height
         let context = canvas.getContext("2d")
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL("image/png") //得到图片的base64编码数据
         let a = document.createElement("a") // 生成一个a元素
        let event = new MouseEvent("click") // 创建一个单击事件
        a.download = name || "photo" // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src =
        file.url.indexOf("b") === 0 ? file.url : this.minio + file.url
        },
    /**
     * 上传文件发送接口
     * @param {*} params
     */
      async uploadFile (params) {
      const _file = params.file
      const formData = new FormData()
      formData.append("file", _file)
       console.dir(formData, "formData")
      const { data } = await uploadFilesAPI(formData)
      if (data.code !== 2000) return
      console.log(data.data.urls[0], "result")
      this.editForm.fileUrl = data.data.urls[0]
      return data
       }
  }
};
</script>
<style lang="scss" scoped>
.uploadImgBOx::v-deep {
 .ck {
    .el-upload--picture-card {
      display: none;
    }
  }
  //  底部提示样式
  & + .upload-demo {
    .el-upload {
      // 不显示 上传按钮
      display: none !important;
    }
  }
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值