Vue+element-ui圖片上傳剪裁組件

index.vue文件vue

<template>
  <div>
    <!-- 多圖片上傳 -->
    <el-upload v-if="multiple" action='string' list-type="picture-card" :on-preview="handlePreview" :auto-upload="false" :on-remove="handleRemove" :http-request="upload" :on-change="consoleFL" :file-list="uploadList">
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 單圖片上傳 -->
    <el-upload v-else class="avatar-uploader" action="'string'" :auto-upload="false" :show-file-list="false" :on-change="handleCrop" :http-request="upload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" ref="singleImg" @mouseenter="mouseEnter" @mouseleave="mouseLeave" :style="{width:width+'px',height:height+'px'}">
      <i v-else class="el-icon-plus avatar-uploader-icon" :style="{width:width+'px',height:height+'px','line-height':height+'px','font-size':height/6+'px'}"></i>
      <!-- 單圖片上傳狀態顯示 -->
      <!-- <div v-if="imageUrl" class="reupload" ref="reupload" @click.stop="handlePreviewSingle" @mouseenter="mouseEnter" @mouseleave="mouseLeave" :style="{width:reuploadWidth+'px',height:reuploadWidth+'px','line-height':reuploadWidth+'px','font-size':reuploadWidth/5+'px'}">從新上傳</div> -->
      <div id="uploadIcon" v-if="imageUrl" ref="reupload" @mouseenter="mouseEnter" @mouseleave="mouseLeave" :style="{width:'100%'}">
        <i class="el-icon-zoom-in" @click.stop="handlePreviewSingle" :style="{color:'#2E2E2E',fontSize:'25px',display:'inline-block',paddingRight:'15px'}"></i>
        <i class="el-icon-upload" :style="{color:'#2E2E2E',fontSize:'25px',display:'inline-block'}"></i>
      </div>
      <div class="reupload" ref="uploading" :style="{width:reuploadWidth+'px',height:reuploadWidth+'px','line-height':reuploadWidth+'px','font-size':reuploadWidth/5+'px'}">上傳中..</div>
      <div class="reupload" ref="failUpload" :style="{width:reuploadWidth+'px',height:reuploadWidth+'px','line-height':reuploadWidth+'px','font-size':reuploadWidth/5+'px'}">上傳失敗</div>
    </el-upload>
    <!-- 多圖片預覽彈窗 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- 剪裁組件彈窗 -->
    <el-dialog :visible.sync="cropperModel" width="800px" :before-close="beforeClose">
      <Cropper :img-file="file" ref="vueCropper" :fixedNumber="fixedNumber" @upload="upload">
      </Cropper>
    </el-dialog>
  </div>
</template>
<script>
import Cropper from '../uploader/cropper'
import axios from '@/assets/js/axios'
export default {
  name: 'uploader',
  props: {
    targetUrl: {
      // 上傳地址
      type: String,
      default: '/storage/upload'
    },
    multiple: {
      // 多圖開關
      type: Boolean,
      default: false
    },
    initUrl: {
      // 初始圖片連接
      default: ''
    },
    fixedNumber: {
      // 剪裁框比例設置
      default: function () {
        return [3, 1]
      }
    },
    width: {
      // 單圖剪裁框寬度
      type: Number,
      default: 178
    },
    height: {
      // 單圖剪裁框高度
      type: Number,
      default: 178
    }
  },
  data () {
    return {
      file: '', // 當前被選擇的圖片文件
      imageUrl: '', // 單圖狀況框內圖片連接
      dialogImageUrl: '', // 多圖狀況彈窗內圖片連接
      uploadList: [], // 上傳圖片列表
      reupload: true, // 控制"從新上傳"開關
      dialogVisible: false, // 展現彈窗開關
      cropperModel: false, // 剪裁組件彈窗開關
      reuploadWidth: this.height * 0.7 // 動態改變」從新上傳「大小
    }
  },
  updated () {
    if (this.$refs.vueCropper) {
      this.$refs.vueCropper.Update()
    }
  },
  watch: {
    initUrl: function (val) {
      // 監聽傳入初始化圖片
      console.info('watch')
      console.info(val)
      if (val) {
        if (typeof this.initUrl === 'string') {
          this.imageUrl = val
        } else {
          this.uploadList = this.formatImgArr(val)
        }
      }
    }
  },
  mounted () {
    if (typeof this.initUrl === 'string') {
      this.imageUrl = this.initUrl
    } else {
      this.uploadList = this.formatImgArr(this.initUrl)
    }
  },
  methods: {
    /** **************************** multiple多圖狀況 **************************************/
    handlePreview (file) {
      // 點擊進行圖片展現
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove (file, fileList) {
      // 刪除圖片後更新圖片文件列表並通知父級變化
      this.uploadList = fileList
      this.$emit('imgupload', this.formatImgArr(this.uploadList))
    },
    consoleFL (file, fileList) {
      // 彈出剪裁框,將當前文件設置爲文件
      this.cropperModel = true
      this.file = file
      this.uploadList = fileList
    },
    /************************************************************************************/

    /****************************** single單圖狀況 **************************************/
    handlePreviewSingle (file) {//點擊進行圖片展現
      this.dialogImageUrl = this.file.url
      this.dialogVisible = true
    },
    mouseEnter () {//鼠標劃入顯示「從新上傳」
      this.$refs.reupload.style.display = 'block'
      if (this.$refs.failUpload.style.display === 'block') {
        this.$refs.failUpload.style.display = 'none'
      }
      this.$refs.singleImg.style.opacity = '0.6'
    },
    mouseLeave () {
      // 鼠標劃出隱藏「從新上傳」
      this.$refs.reupload.style.display = 'none'
      this.$refs.singleImg.style.opacity = '1'
    },
    handleCrop (file, files) {
      // 點擊彈出剪裁框
      this.cropperModel = true
      this.file = file
      // this.imageUrl = file.url
    },
    /************************************************************************************/

    upload (data) {
      // 自定義upload事件
      if (!this.multiple) {
        // 若是單圖,則顯示正在上傳
        this.$refs.uploading.style.display = 'block'
      }
      let formData = new FormData()
      formData.append('attachment', data)
      axios.post(this.targetUrl, formData).then(res => {
        if (!this.multiple) {
          // 上傳完成後隱藏正在上傳
          this.$refs.uploading.style.display = 'none'
        }
        if (res.msg === 'success') {
          // 上傳成功將照片傳回父組件
          const currentPic = res.data.url
          if (this.multiple) {
            this.uploadList.push({
              url: currentPic,
              uid: '111'
            })
            this.uploadList.pop()
            this.$emit('imgupload', this.formatImgArr(this.uploadList))
          } else {
            this.$emit('imgupload', currentPic)
          }
        } else {
          // 上傳失敗則顯示上傳失敗,如多圖則從圖片列表刪除圖片
          if (!this.multiple) {
            this.$refs.failUpload.style.display = 'block'
          } else {
            this.uploadList.pop()
          }
        }
      })
      this.cropperModel = false
    },
    formatImgArr (arr) {
      const result = arr.map((item, index) => {
        if (typeof item === 'string') {
          return {
            url: item,
            uid: `index${index}`
          }
        } else {
          return item.url
        }
      })
      return result
    },
    beforeClose (done) {
      this.uploadList.pop()
      this.cropperModel = false
    }
  },
  components: {
    Cropper
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    color: #8c939d;
    text-align: center;
  }
  .avatar {
    display: block;
  }
  .reupload {
    border-radius: 50%;
    position: absolute;
    color: #fff;
    background-color: #000000;
    opacity: 0.6;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none;
  }
  #uploadIcon{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none;
  }
</style>
複製代碼

cropper.vue文件ios

<template>
  <div>
    <div class="cropper-content">
      <!-- 剪裁框 -->
      <div class="cropper">
        <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox" @realTime="realTime" :fixed="option.fixed" :fixedNumber="fixedNumber"></vueCropper>
      </div>
      <!-- 預覽框 -->
      <div class="show-preview" :style="{'width': '300px', 'height': '300px', 'overflow': 'hidden', 'margin': '0 25px', 'display':'flex', 'align-items' : 'center'}">
        <div :style="previews.div" class="preview">
          <img :src="previews.url" :style="previews.img">
        </div>
      </div>
    </div>
    <div class="footer-btn">
      <!-- 縮放旋轉按鈕 -->
      <div class="scope-btn">
        <el-button type="primary" icon="el-icon-zoom-in" @click="changeScale(1)"></el-button>
        <el-button type="primary" icon="el-icon-zoom-out" @click="changeScale(-1)"></el-button>
        <el-button type="primary" @click="rotateLeft">逆時針旋轉</el-button>
        <el-button type="primary" @click="rotateRight">順時針旋轉</el-button>
      </div>
      <!-- 確認上傳按鈕 -->
      <div class="upload-btn">
        <el-button type="primary" @click="uploadImg('blob')">上傳</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import VueCropper from 'vue-cropper'
export default {
  data () {
    return {
      previews: {}, // 預覽數據
      option: {
        img: '', // 裁剪圖片的地址  (默認:空)
        size: 1, // 裁剪生成圖片的質量  (默認:1)
        full: true, // 是否輸出原圖比例的截圖 選true生成的圖片會很是大  (默認:false)
        outputType: 'png', // 裁剪生成圖片的格式  (默認:jpg)
        canMove: true, // 上傳圖片是否能夠移動  (默認:true)
        original: false, // 上傳圖片按照原始比例渲染  (默認:false)
        canMoveBox: true, // 截圖框可否拖動  (默認:true)
        autoCrop: true, // 是否默認生成截圖框  (默認:false)
        autoCropWidth: 400, // 默認生成截圖框寬度  (默認:80%)
        autoCropHeight: 400, // 默認生成截圖框高度  (默認:80%)
        fixedBox: false, // 固定截圖框大小 不容許改變  (默認:false)
        fixed: true, // 是否開啓截圖框寬高固定比例  (默認:true)
        fixedNumber: [1.5, 1] // 截圖框比例  (默認:[1:1])
      },
      downImg: '#'
    }
  },
  props: ['imgFile', 'fixedNumber'],
  methods: {
    changeScale (num) {
      // 圖片縮放
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    rotateLeft () {
      // 向左旋轉
      this.$refs.cropper.rotateLeft()
    },
    rotateRight () {
      // 向右旋轉
      this.$refs.cropper.rotateRight()
    },
    Update () {
      // this.file = this.imgFile
      this.option.img = this.imgFile.url
    },
    realTime (data) {
      // 實時預覽
      this.previews = data
    },
    uploadImg (type) {
      // 將剪裁好的圖片回傳給父組件
      event.preventDefault()
      let that = this
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob(data => {
          that.$emit('upload', data)
        })
      } else {
        this.$refs.cropper.getCropData(data => {
          that.$emit('upload', data)
        })
      }
    }
  },
  components: { VueCropper }
}
</script>
<style>
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}
.cropper-content .cropper {
  width: 350px;
  height: 300px;
}
.cropper-content .show-preview {
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
  overflow: hidden;
  border: 1px solid #cccccc;
  background: #cccccc;
  margin-left: 40px;
}
.preview {
  overflow: hidden;
  border: 1px solid #cccccc;
  background: #cccccc;
}
.footer-btn {
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}
.footer-btn .scope-btn {
  width: 250px;
  display: flex;
  display: -webkit-flex;
  justify-content: space-between;
  -webkit-justify-content: space-between;
}
.footer-btn .upload-btn {
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
}
.footer-btn .btn {
  outline: none;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  -webkit-appearance: none;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  -webkit-transition: 0.1s;
  transition: 0.1s;
  font-weight: 500;
  padding: 8px 15px;
  font-size: 12px;
  border-radius: 3px;
  color: #fff;
  background-color: #67c23a;
  border-color: #67c23a;
}
</style>
複製代碼

效果:web

可選上傳地址,剪裁比例,圖片框大小,多圖單圖等....axios

相關文章
相關標籤/搜索