1. 程式人生 > 程式設計 >vue 圖片裁剪上傳元件的實現

vue 圖片裁剪上傳元件的實現

先看一下總體效果:

上傳檔案做了大小和型別的限制,在動圖中無法展現出來。

vue 圖片裁剪上傳元件的實現

使用file型別的input實現選擇本地檔案

但是瀏覽器原生的檔案上傳按鈕的顏值不盡人意,而且按鈕上的文字是無法改變的,我需要把這個上傳檔案的按鈕改造一下。

  • 方法1:使用label元素來觸發一個隱藏的file型別的 input元素;(缺點:在多人開發時,可能出現重複的元素id,導致難以預料的bug)
<input type="file" id='up_file_input' v-show='false' >
<label for='up_file_input'></label>
  • 方法2:或者在這個label元素的click事件函式中手動觸發檔案上傳按鈕的click事件。
<input type="file" v-show='false' ref="inputFileUp" >
<label @click='$refs.inputFileUp.click()'></label>

使用input的change事件獲取選擇的本地圖片並進行校驗

上傳圖片的校驗規則及提示語由父元件通過 prop 傳遞給子元件,格式如下:

const img_valit = {
 type: /^.*\.(jpg|png|jpeg)$/i,// 檔案格式校驗
 type_error_msg: '上傳頭像圖片只能是 jpg 或者 png 格式!',size: 3,// 檔案大小校驗
 size_error_msg: '上傳的圖片大小不能超過3MB'
}

這裡需要注意: 需要在上傳檔案按鈕的click事件中手動清空這個檔案型別輸入框的值,解決選擇和上次相同的檔案之後無法觸發 change事件的問題

function fileInputClick(event) {
  event.target.value = "";
}
function coverImgChange(event) {
   const file = event.target.files[0];
   // 在元件的自定義屬性中定義一個變數 originalFile 來儲存當前上傳的檔案
   this.$options._myOpt.originalFile = file;
   // 獲取對檔案的校驗規則
   const { type,size,type_error_msg,size_error_msg } = this.img_valit;
   // 校驗檔案型別和檔案大小
   const isJPG_PNG = type.test(file.name),isLt5M = file.size / 1024 / 1024 <= size;
   !isLt5M && this.$message.error(size_error_msg);
   !isJPG_PNG && this.$message.error(type_error_msg);
   // 檔案通過校驗,開啟裁剪彈窗
   if (isJPG_PNG && isLt5M) {
    this.cropImgUrl = window.URL.createObjectURL(file);
    this.dialogVisible = true;
   }
  }

開啟彈窗進行圖片裁剪

彈窗使用的 Element-UI 中的彈窗,圖片裁剪是第三方外掛 vue-cropper。圖片裁剪外掛中的一些配置可以參考外掛官方文件,下面的程式碼中省略了配置部分的程式碼。

<el-dialog :visible.sync="dialogVisible" width='800px' title="圖片裁剪">
   <div class="dialog-content">
    <div class="cropper-image">
     <vue-cropper
      ref="cropper"
      :img="cropImgUrl"
      @realTime="realTime"
     ></vue-cropper>
    </div>
    <!-- 圖片裁剪之後的預覽 -->
    <div class="preview-wrapper">
     <div
      class="show-preview"
      :style="{'width': previews.w + 'px','height': previews.h + 'px','overflow': 'hidden'}"
     >
      <div :style="previews.div">
       <img :src="previews.url" class="preview_img" :style="[previews.img]">
      </div>
     </div>
     <p class="preview-text">裁剪結果預覽</p>
    </div>
   </div>
   <div slot="footer" class="dialog-footer">
    <button @click="dialogEsc()">取 消</button>
    <button @click="dialogSure()">確 定</button>
   </div>
  </el-dialog>

向伺服器傳送請求上傳圖片

上傳檔案介面中,向後臺傳送請求的引數為 {image: 檔案本身(File型別),filename: 檔名}

function realTime(data) {
  this.previews = data;
}
// 裁剪彈窗中確定按鈕的點選事件
function dialogSure() {
   const ajaxConfig = {
    headers: {
     "Content-Type": "multipart/form-data"
    }
   };
   // 上傳圖片的檔名
   let cropFileName =
    this.$options._myOpt.originalFile.name.match(/([^\/]+)(?=\.)/gi)[0] ||
    Date.now().toString();
   this.$refs.cropper.getCropBlob(blob => {
   // IE 和 Edge 不支援 File 建構函式
    let cropFile = new File(
     [blob],cropFileName.toString() + "." + (this.cropperConfig.outputType || "jpg"),{ type: blob.type }
    );
    let upParams = new FormData();
    upParams.append("image",cropFile);
    upParams.append("filename",cropFile.fileName);
    axios.post(this.up_action,upParams).then(({ data }) => {
     if (data.status === 0) {
      this.coverUlr = window.URL.createObjectURL(blob);
      this.pathToParent({
       fileId: data.result.fileId,fileExt: data.result.fileExt
      });
     } else {
      this.coverUlr = "";
      this.pathToParent({
       fileId: "",fileExt: ""
      });
     }
    });
   });
   this.dialogVisible = false;
  }
  // 向父元件傳遞上傳檔案成功之後後臺返回的資料
  function pathToParent(filePath) {
   this.$emit("getFilePath",filePath);
  }

以上就是vue 圖片裁剪上傳元件的實現的詳細內容,更多關於vue 圖片裁剪上傳元件的資料請關注我們其它相關文章!