el-upload配合vue-cropper實現上傳圖片前裁剪
- 2020 年 6 月 6 日
- 筆記
- cropper, el-upload+cropper, javascript, VUE, vue-cropper, 裁剪
需求背景
上傳一個封面圖,在上傳之前需要對圖片進行裁剪,上傳裁剪之後的圖片,類似微信的上傳頭像。
技術方案
上傳肯定是用element的 el-upload 組件實現上傳,非常方便,各種鉤子函數。
裁剪一開始找的 cropper 看著功能到是非常齊全,api也比較豐富,基本是符合預期的需求的。但是此庫是基於jq 的,在vue項目中有點難用。於是就找到了 vue-cropper 支援組件化的方式,只需要傳入相應的配置參數就可以使用,還有一個非常方便的地方是 官網 提供了在線調試頁面,更改配置就可以看到效果,配置好之後再把程式碼複製到項目中,也是相當的方便。
封裝組件
上傳文件的組件:uploadImg.vue
<template> <div :class="$options.name"> <el-upload v-show="!resultImg" class="upload-el" accept="image/*" ref="fileUpload" name="pic" :action="action" :data="uploadData" :on-change="selectChange" :show-file-list="false" :auto-upload="false" :http-request="httpRequest"> <div> <span class="icon upload-icon" /> <el-button>選擇圖片</el-button> </div> <div slot="tip" class="el-upload__tip"> 圖片大小不超過5M,推薦圖片尺寸寬高比9:16 </div> </el-upload> <figure v-show="resultImg" class="result-img"> <img :src="resultImg"> <el-button @click="updateCropper">重新上傳</el-button> </figure> <cropper v-if="showCropper" :dialog-visible="showCropper" :cropper-img="cropperImg" @update-cropper="updateCropper" @colse-dialog="closeDialog" @upload-img="uploadImg" /> </div> </template> <script> import Cropper from './cropper.vue'; import { baseAxios } from '@common/axios'; import { loading } from '@common'; export default { name: 'UploadImg', components: { Cropper }, data () { return { uploadData: { // 上傳需要的額外參數 siteId: 1, source: 1 }, action: '/mvod-aliyun/material/uplod/pic', // 上傳地址,必填 cropperImg: '', // 需要裁剪的圖片 showCropper: false, // 是否顯示裁剪框 uploadFile: '', // 裁剪後的文件 resultImg: '' // 上傳成功,後台返回的路徑 }; }, methods: { // submit 之後會觸發此方法 httpRequest (request) { const { action, data, filename } = request; // 新建formDate對象 let formData = new FormData(); for (let key in data) { formData.append(key, data[key]); } // 文件單獨push,第三個參數指定上傳的文件名 formData.append(filename, this.uploadFile, data.fileName); loading.start(); // 上傳中的loading baseAxios({ headers: { contentType: 'multipart/form-data' // 需要指定上傳的方式 }, url: action, method: 'post', data: formData, timeout: 200000000 // 防止文件過大超時 }).then(({ data: resp }) => { loading.close(); const { code, data, msg } = resp || {}; if (code === 0) { this.$message.success('圖片上傳成功'); this.resultImg = data; // 上傳成功後展示的圖片 } else { this.$message.error(msg || '網路錯誤'); } }).catch(err => { loading.close(); console.log(err); }); }, // 選擇文件 selectChange (file) { const { raw } = file; this.openCropper(raw); }, /** * @param {file} 上傳的文件 */ openCropper (file) { var files = file; let isLt5M = files.size > (5 << 20); if (isLt5M) { this.$message.error('請上傳5M內的圖片'); return false; } var reader = new FileReader(); reader.onload = e => { let data; if (typeof e.target.result === 'object') { // 把Array Buffer轉化為blob 如果是base64不需要 data = window.URL.createObjectURL(new Blob([e.target.result])); } else { data = e.target.result; } this.cropperImg = data; }; // 轉化為base64 // reader.readAsDataURL(file) // 轉化為blob reader.readAsArrayBuffer(files); this.showCropper = true; }, // 上傳圖片 uploadImg (file) { this.uploadFile = file; this.$refs.fileUpload.submit(); }, // 更新圖片 updateCropper () { this.$refs.fileUpload.$children[0].$el.click(); }, // 關閉窗口 closeDialog () { this.showCropper = false; } } }; </script> <style lang="scss" scoped> .UploadImg { .video-image { display: flex; figure { width: 100px; img { width: 100%; display: block; } } } } </style>
封裝裁剪組件 cropper.vue
<template> <div :class="$options.name"> <el-dialog :visible.sync="dialogVisible" width="600px" :before-close="handleClose"> <div class="cropper-container"> <div class="cropper-el"> <vue-cropper ref="cropper" :img="cropperImg" :output-size="option.size" :output-type="option.outputType" :info="true" :full="option.full" :can-move="option.canMove" :can-move-box="option.canMoveBox" :fixed-box="option.fixedBox" :original="option.original" :auto-crop="option.autoCrop" :auto-crop-width="option.autoCropWidth" :auto-crop-height="option.autoCropHeight" :center-box="option.centerBox" :high="option.high" :info-true="option.infoTrue" @realTime="realTime" :enlarge="option.enlarge" :fixed="option.fixed" :fixed-number="option.fixedNumber" /> </div> <!-- 預覽 --> <div class="prive-el"> <div class="prive-style" :style="{'width': '150px', 'height': '266px', 'overflow': 'hidden', 'margin': '0 25px', 'display':'flex', 'align-items' : 'center'}"> <div class="preview" :style="previews.div"> <img :src="previews.url" :style="previews.img"> </div> </div> <el-button @click="uploadBth" v-if="option.img">重新上傳</el-button> </div> </div> <span slot="footer" class="dialog-footer"> <el-button @click="handleClose">取 消</el-button> <el-button type="primary" @click="saveImg">確 定</el-button> </span> </el-dialog> </div> </template> <script> import { VueCropper } from 'vue-cropper'; export default { name: 'Cropper', components: { VueCropper }, props: { dialogVisible: { type: Boolean, default: false }, imgType: { type: String, default: 'blob' }, cropperImg: { type: String, default: '' } }, data () { return { previews: {}, option: { img: '', // 裁剪圖片的地址 size: 1, // 裁剪生成圖片的品質 full: false, // 是否輸出原圖比例的截圖 默認false outputType: 'png', // 裁剪生成圖片的格式 默認jpg canMove: false, // 上傳圖片是否可以移動 fixedBox: false, // 固定截圖框大小 不允許改變 original: false, // 上傳圖片按照原始比例渲染 canMoveBox: true, // 截圖框能否拖動 autoCrop: true, // 是否默認生成截圖框 // 只有自動截圖開啟 寬度高度才生效 autoCropWidth: 200, // 默認生成截圖框寬度 autoCropHeight: 150, // 默認生成截圖框高度 centerBox: true, // 截圖框是否被限制在圖片裡面 high: false, // 是否按照設備的dpr 輸出等比例圖片 enlarge: 1, // 圖片根據截圖框輸出比例倍數 mode: 'contain', // 圖片默認渲染方式 maxImgSize: 2000, // 限制圖片最大寬度和高度 limitMinSize: [100, 120], // 更新裁剪框最小屬性 infoTrue: false, // true 為展示真實輸出圖片寬高 false 展示看到的截圖框寬高 fixed: true, // 是否開啟截圖框寬高固定比例 (默認:true) fixedNumber: [9, 16] // 截圖框的寬高比例 } }; }, methods: { // 裁剪時觸發的方法,用於實時預覽 realTime (data) { this.previews = data; }, // 重新上傳 uploadBth () { this.$emit('update-cropper'); }, // 取消關閉彈框 handleClose () { this.$emit('colse-dialog', false); }, // 獲取裁剪之後的圖片,默認blob,也可以獲取base64的圖片 saveImg () { if (this.imgType === 'blob') { this.$refs.cropper.getCropBlob(data => { this.$emit('upload-img', data); }); } else { this.$refs.cropper.getCropData(data => { this.uploadFile = data; this.$emit('upload-img', data); }); } } } }; </script> <style lang="scss" scoped> .Cropper { .cropper-el { height: 300px; width: 300px; } .cropper-container { display: flex; justify-content: space-between; .prive-el { height: 164px; width: 94px; flex: 1; text-align: center; .prive-style { margin: 0 auto; flex: 1; -webkit-flex: 1; display: flex; display: -webkit-flex; justify-content: center; -webkit-justify-content: center; overflow: hidden; background: #ededed; margin-left: 40px; } .preview { overflow: hidden; } .el-button { margin-top: 20px; } } } } </style>
效果截圖
問題總結
問題一、如何阻止upload上傳完之後就上傳?
將el-upload 的 auto-upload 設置為 false即可
問題二、如何將獲取到文件傳給vue-cropper?
vue-cropper 可以接受一個 blob,此時需要 new FileReader(),參考 MDN
問題三、el-upload 選擇完文件後不能更改,如何上傳裁剪之後的圖片?
此問題在網上查到兩種思路:
1. 使用 this.$refs.fileUpload.$children[0].post(files) 方法可以更改上傳的文件,調用此方法就會自動觸發文件上,不用在調用submit,但是el-upload內部會報個錯,file.status is not defined,並且不會觸發before-upload和onsuccess,無法拿到上傳之後的結果,具體原因沒細查。
2. 使用自定義上傳,點擊上傳時直接調用submit 方法,這時會自動觸發http-request中的自定義方法,可以拿到file中的所有屬性,在函數裡面使用 axios 自定義上傳參數和文件。此方法比較好控制,本文也是採用的次方法進行上傳。
參考
官方example源程式碼://github.com/xyxiao001/vue-cropper/blob/master/example/src/App.vue