Vue项目图片剪切上传——vue-cropper的使用(二)
真实例子
<template> <div class="cutimg"> <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :fixedBox="option.fixedBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" @realTime="realTime" ></vueCropper> <a @click="down()" class="btn">download(base64)</a> <a @click="down()" class="btn">download(blob)</a> <label class="btn" for="uploads">upload</label> <el-button @click="upupup">上传</el-button> <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)"> <div class="show-preview" :style="{'width': previews.w + 'px', 'height': previews.h + 'px', 'overflow': 'hidden', 'margin': '5px'}"> <div :style="previews.div"> <img :src="previews.url" :style="previews.img"> </div> </div> <img :src="downImg"/> </div> </template> <script> import axios from 'axios/index' import util from '@/utils/util' export default { props: { uploadProps: { type: Object, validator(value) { const keys = Object.keys(value); if (!Object.keys(value).includes("action")) { throw "action url is required"; } return true; } } }, data() { return { previews: {}, downImg: '', fileName: null, option: { img: 'https://fengyuanchen.github.io/cropper/images/picture.jpg', size: 1, full: false, outputType: 'png', canMove: false, fixedBox: false, original: false, canMoveBox: true, autoCrop: true, autoCropWidth: 750, autoCropHeight: 200 }, } }, methods: { // 实时预览函数 realTime(data) { this.previews = data }, uploadImg(e) { console.log(e) //上传图片 var file = e.target.files[0]; this.fileName = file.name; if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) { alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种') 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.option.img = data } // 转化为blob reader.readAsArrayBuffer(file); }, down() { this.$refs.cropper.getCropBlob((data) => { this.downImg = window.URL.createObjectURL(data) var reader = new FileReader(); reader.readAsArrayBuffer(data); }) }, upupup() { let formData = new FormData(); this.$refs.cropper.getCropBlob((data) => { let img = window.URL.createObjectURL(data) this.model = true; this.modelSrc = img; formData.append("file", data, this.fileName); console.log(formData) let config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } axios.post(process.env.BASE_URL + '/oss/upload', formData, config).then((res) => { console.log(res) }) }) }, } } </script> <style scoped> .vue-cropper { height: 500px; } .btn { background: #86a6ff; } </style>