最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

vue中上传图片并裁剪

IT圈 admin 2浏览 0评论

vue中上传图片并裁剪

先安装

npm install vue-cropper // npm 安装
yarn add vue-cropper // yarn 安装

 引用

// 全局引用

main.js import VueCropper from 'vue-cropper'

Vue.use(VueCropper) 

上传按钮

<el-upload:class="{hide:hideUpload}"multiple:file-list="imageUrl1":action="action"list-type="picture-card":on-preview="handlePictureCardPreview":on-remove="handleRemove":limit="limit":headers="headers":on-success="handleAvatarSuccess":on-exceed="handleExceed":before-remove="beforeRemove"><i class="el-icon-plus"></i></el-upload>

 弹出的裁剪框

 

<!-- vueCropper 剪裁图片实现--><el-dialogtitle="图片剪裁":visible.sync="dialogVisible"class="crop-dialog"append-to-body><div class="cropper-content"><div class="cropper" style="text-align: center"><vueCropperref="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":fixed="option.fixed":fixedNumber="option.fixedNumber":centerBox="option.centerBox":infoTrue="option.infoTrue":fixedBox="option.fixedBox":autoCropWidth="option.autoCropWidth":autoCropHeight="option.autoCropHeight"@cropMoving="cropMoving"/></div></div><div class="action-box"><!-- <el-uploadclass="upload-demo"action="":auto-upload="false":show-file-list="false":on-change="handleAvatarSuccess"> --><!-- <el-upload:class="{hide:hideUpload}"multiple:file-list="imageUrl1":action="action":on-preview="handlePictureCardPreview":on-remove="handleRemove":limit="limit":headers="headers":on-success="handleAvatarSuccess":on-exceed="handleExceed":before-remove="beforeRemove":show-file-list="false"><el-button type="primary" plain>更换图片</el-button></el-upload> --><!-- <el-button type="primary" plain @click="clearImgHandle">清除图片</el-button> --><el-button type="primary" plain @click="rotateLeftHandle">左旋转</el-button><el-button type="primary" plain @click="rotateRightHandle">右旋转</el-button><el-button type="primary" plain @click="changeScaleHandle(1)">放 大</el-button><el-button type="primary" plain @click="changeScaleHandle(-1)">缩 小</el-button><!-- <el-button type="primary" plain @click="downloadHandle('blob')">下载</el-button> --></div><div slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="finish" :loading="loading">确 认</el-button></div></el-dialog>

 

data(){return {dialogimgVisible: false,action: process.env.VUE_APP_BASE_API + "/ksUser/submitAttachment",headers: {},imageUrl1: [],// 裁剪框isPreview: false,dialogVisible: false,previewImg: "", // 预览图片地址// 裁剪组件的基础配置optionoption: {img: "", // 裁剪图片的地址info: true, // 裁剪框的大小信息outputSize: 1, // 裁剪生成图片的质量outputType: "png", // 裁剪生成图片的格式canScale: true, // 图片是否允许滚轮缩放autoCrop: true, // 是否默认生成截图框canMoveBox: true, // 截图框能否拖动autoCropWidth: 0, // 默认生成截图框宽度autoCropHeight: 0, // 默认生成截图框高度fixedBox: true, // 固定截图框大小 不允许改变fixed: true, // 是否开启截图框宽高固定比例fixedNumber: [1, 1], // 截图框的宽高比例full: false, // 是否输出原图比例的截图original: false, // 上传图片按照原始比例渲染centerBox: false, // 截图框是否被限制在图片里面infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高},// 防止重复提交loading: false,fileNames: "", //图片的名称imgList: [],}
}

 

methods: {handleRemove(file, fileList) {console.log(file, fileList);},handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogimgVisible = true;},// 上传成功handleAvatarSuccess(res, file) {// console.log(res, "上传");console.log(file, "上传成功文件");// console.log(this.imgIndex, "第几个上传");this.fileNames = file.response.name;this.imageUrl1.push(file.response);this.hideUpload = this.imageUrl1.length >= this.limit;// 上传成功后将图片地址赋值给裁剪框显示图片if (this.option.autoCropWidth != 0) {this.$nextTick(async () => {// base64方式// this.option.img = await fileByBase64(file.raw)this.option.img = file.response.url;this.loading = false;this.dialogVisible = true;});} else {// var imgs = [];this.imgList.push(file.response.fileName);this.$emit("getUpload", this.imgList);}},// 放大/缩小changeScaleHandle(num) {num = num || 1;this.$refs.cropper.changeScale(num);},// 左旋转rotateLeftHandle() {this.$refs.cropper.rotateLeft();},// 右旋转rotateRightHandle() {this.$refs.cropper.rotateRight();},// 下载downloadHandle(type) {let aLink = document.createElement("a");aLink.download = "author-img";if (type === "blob") {this.$refs.cropper.getCropBlob((data) => {let downImg = window.URL.createObjectURL(data);aLink.href = window.URL.createObjectURL(data);aLink.click();});} else {this.$refs.cropper.getCropData((data) => {let downImg = data;aLink.href = data;aLink.click();});}},// 清理图片clearImgHandle() {this.option.img = "";},// 截图框移动回调函数cropMoving(data) {// 截图框的左上角 x,y和右下角坐标x,y// let cropAxis = [data.axis.x1, data.axis.y1, data.axis.x2, data.axis.y2]// console.log(cropAxis)},finish() {// 获取截图的 blob 数据// this.$refs.cropper.getCropBlob((blob) => {//   console.log(blob, "blob数据");//   this.loading = true;//   this.dialogVisible = false;//   this.previewImg = URL.createObjectURL(blob);//   console.log(this.previewImg, "this.previewImg确认");//   this.isPreview = true;// });// 获取截图的 base64 数据this.loading = true;this.$refs.cropper.getCropData((data) => {// console.log(data, "获取截图的 base64 数据");var fileNamed = this.base64ToFile(data, this.fileNames);// console.log(fileNamed, "fileNamed图片转换成的filename ");let formData = new FormData();formData.append("file", fileNamed); //非常重要的一步 这是将base64转换成file传给后端的关键// formData.append("flag", "videoImg"); // 额外参数submitAttachment(formData).then((res) => {if (res.code == 200) {this.$message.success("上传成功");this.imgList.push(res.fileName);this.$emit("getUpload", this.imgList);//将上传完成的图片传给父组件this.dialogVisible = false;}});});},//将base64格式转换为文件格式,因为我这向后台提交数据时需要文件格式base64ToFile(urlData, fileName) {let arr = urlData.split(",");let mime = arr[0].match(/:(.*?);/)[1];let bytes = atob(arr[1]); // 解码base64let n = bytes.length;let ia = new Uint8Array(n);while (n--) {ia[n] = bytes.charCodeAt(n);}return new File([ia], fileName, { type: mime });},// 限制选择handleExceed(files, fileList) {this.$message.warning(`当前限制选择${this.limit}个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);},// 移除beforeRemove(file, fileList) {this.$confirm(`确定移除该图片?`, "提示", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning",}).then(() => {const filePath = file.url;const i = this.imageUrl1.findIndex((x) => x.url === filePath);// 3.调用splice方法,移除图片信息this.imageUrl1.splice(i, 1);if (this.imgIndex == 1) {this.list.householdRegisters.splice(i, 1);// this.list.householdRegisters = "";this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 2) {// this.list.idPhotos = "";this.list.idPhotos.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 3) {// this.list.diplomas = "";this.list.diplomas.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 4) {// this.list.proofOfEmployments = "";this.list.proofOfEmployments.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 5) {// this.list.honorCertificates = "";this.list.honorCertificates.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 6) {// this.list.videoUploads = "";this.list.videoUploads.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}this.$message({type: "success",message: "删除成功!",});}).catch(() => {this.$message({type: "info",message: "已取消删除",});});},},

是参照这位博主的改进的  仅作为本人的学习积累笔记  如有侵权 私信我删除谢谢vue+element实现图片上传及裁剪功能(vue-cropper)_努力搬砖的阿一的博客-CSDN博客_element 图片裁切

vue中上传图片并裁剪

先安装

npm install vue-cropper // npm 安装
yarn add vue-cropper // yarn 安装

 引用

// 全局引用

main.js import VueCropper from 'vue-cropper'

Vue.use(VueCropper) 

上传按钮

<el-upload:class="{hide:hideUpload}"multiple:file-list="imageUrl1":action="action"list-type="picture-card":on-preview="handlePictureCardPreview":on-remove="handleRemove":limit="limit":headers="headers":on-success="handleAvatarSuccess":on-exceed="handleExceed":before-remove="beforeRemove"><i class="el-icon-plus"></i></el-upload>

 弹出的裁剪框

 

<!-- vueCropper 剪裁图片实现--><el-dialogtitle="图片剪裁":visible.sync="dialogVisible"class="crop-dialog"append-to-body><div class="cropper-content"><div class="cropper" style="text-align: center"><vueCropperref="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":fixed="option.fixed":fixedNumber="option.fixedNumber":centerBox="option.centerBox":infoTrue="option.infoTrue":fixedBox="option.fixedBox":autoCropWidth="option.autoCropWidth":autoCropHeight="option.autoCropHeight"@cropMoving="cropMoving"/></div></div><div class="action-box"><!-- <el-uploadclass="upload-demo"action="":auto-upload="false":show-file-list="false":on-change="handleAvatarSuccess"> --><!-- <el-upload:class="{hide:hideUpload}"multiple:file-list="imageUrl1":action="action":on-preview="handlePictureCardPreview":on-remove="handleRemove":limit="limit":headers="headers":on-success="handleAvatarSuccess":on-exceed="handleExceed":before-remove="beforeRemove":show-file-list="false"><el-button type="primary" plain>更换图片</el-button></el-upload> --><!-- <el-button type="primary" plain @click="clearImgHandle">清除图片</el-button> --><el-button type="primary" plain @click="rotateLeftHandle">左旋转</el-button><el-button type="primary" plain @click="rotateRightHandle">右旋转</el-button><el-button type="primary" plain @click="changeScaleHandle(1)">放 大</el-button><el-button type="primary" plain @click="changeScaleHandle(-1)">缩 小</el-button><!-- <el-button type="primary" plain @click="downloadHandle('blob')">下载</el-button> --></div><div slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="finish" :loading="loading">确 认</el-button></div></el-dialog>

 

data(){return {dialogimgVisible: false,action: process.env.VUE_APP_BASE_API + "/ksUser/submitAttachment",headers: {},imageUrl1: [],// 裁剪框isPreview: false,dialogVisible: false,previewImg: "", // 预览图片地址// 裁剪组件的基础配置optionoption: {img: "", // 裁剪图片的地址info: true, // 裁剪框的大小信息outputSize: 1, // 裁剪生成图片的质量outputType: "png", // 裁剪生成图片的格式canScale: true, // 图片是否允许滚轮缩放autoCrop: true, // 是否默认生成截图框canMoveBox: true, // 截图框能否拖动autoCropWidth: 0, // 默认生成截图框宽度autoCropHeight: 0, // 默认生成截图框高度fixedBox: true, // 固定截图框大小 不允许改变fixed: true, // 是否开启截图框宽高固定比例fixedNumber: [1, 1], // 截图框的宽高比例full: false, // 是否输出原图比例的截图original: false, // 上传图片按照原始比例渲染centerBox: false, // 截图框是否被限制在图片里面infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高},// 防止重复提交loading: false,fileNames: "", //图片的名称imgList: [],}
}

 

methods: {handleRemove(file, fileList) {console.log(file, fileList);},handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogimgVisible = true;},// 上传成功handleAvatarSuccess(res, file) {// console.log(res, "上传");console.log(file, "上传成功文件");// console.log(this.imgIndex, "第几个上传");this.fileNames = file.response.name;this.imageUrl1.push(file.response);this.hideUpload = this.imageUrl1.length >= this.limit;// 上传成功后将图片地址赋值给裁剪框显示图片if (this.option.autoCropWidth != 0) {this.$nextTick(async () => {// base64方式// this.option.img = await fileByBase64(file.raw)this.option.img = file.response.url;this.loading = false;this.dialogVisible = true;});} else {// var imgs = [];this.imgList.push(file.response.fileName);this.$emit("getUpload", this.imgList);}},// 放大/缩小changeScaleHandle(num) {num = num || 1;this.$refs.cropper.changeScale(num);},// 左旋转rotateLeftHandle() {this.$refs.cropper.rotateLeft();},// 右旋转rotateRightHandle() {this.$refs.cropper.rotateRight();},// 下载downloadHandle(type) {let aLink = document.createElement("a");aLink.download = "author-img";if (type === "blob") {this.$refs.cropper.getCropBlob((data) => {let downImg = window.URL.createObjectURL(data);aLink.href = window.URL.createObjectURL(data);aLink.click();});} else {this.$refs.cropper.getCropData((data) => {let downImg = data;aLink.href = data;aLink.click();});}},// 清理图片clearImgHandle() {this.option.img = "";},// 截图框移动回调函数cropMoving(data) {// 截图框的左上角 x,y和右下角坐标x,y// let cropAxis = [data.axis.x1, data.axis.y1, data.axis.x2, data.axis.y2]// console.log(cropAxis)},finish() {// 获取截图的 blob 数据// this.$refs.cropper.getCropBlob((blob) => {//   console.log(blob, "blob数据");//   this.loading = true;//   this.dialogVisible = false;//   this.previewImg = URL.createObjectURL(blob);//   console.log(this.previewImg, "this.previewImg确认");//   this.isPreview = true;// });// 获取截图的 base64 数据this.loading = true;this.$refs.cropper.getCropData((data) => {// console.log(data, "获取截图的 base64 数据");var fileNamed = this.base64ToFile(data, this.fileNames);// console.log(fileNamed, "fileNamed图片转换成的filename ");let formData = new FormData();formData.append("file", fileNamed); //非常重要的一步 这是将base64转换成file传给后端的关键// formData.append("flag", "videoImg"); // 额外参数submitAttachment(formData).then((res) => {if (res.code == 200) {this.$message.success("上传成功");this.imgList.push(res.fileName);this.$emit("getUpload", this.imgList);//将上传完成的图片传给父组件this.dialogVisible = false;}});});},//将base64格式转换为文件格式,因为我这向后台提交数据时需要文件格式base64ToFile(urlData, fileName) {let arr = urlData.split(",");let mime = arr[0].match(/:(.*?);/)[1];let bytes = atob(arr[1]); // 解码base64let n = bytes.length;let ia = new Uint8Array(n);while (n--) {ia[n] = bytes.charCodeAt(n);}return new File([ia], fileName, { type: mime });},// 限制选择handleExceed(files, fileList) {this.$message.warning(`当前限制选择${this.limit}个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);},// 移除beforeRemove(file, fileList) {this.$confirm(`确定移除该图片?`, "提示", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning",}).then(() => {const filePath = file.url;const i = this.imageUrl1.findIndex((x) => x.url === filePath);// 3.调用splice方法,移除图片信息this.imageUrl1.splice(i, 1);if (this.imgIndex == 1) {this.list.householdRegisters.splice(i, 1);// this.list.householdRegisters = "";this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 2) {// this.list.idPhotos = "";this.list.idPhotos.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 3) {// this.list.diplomas = "";this.list.diplomas.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 4) {// this.list.proofOfEmployments = "";this.list.proofOfEmployments.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 5) {// this.list.honorCertificates = "";this.list.honorCertificates.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}if (this.imgIndex == 6) {// this.list.videoUploads = "";this.list.videoUploads.splice(i, 1);this.hideUpload = this.imageUrl1.length >= this.limit;}this.$message({type: "success",message: "删除成功!",});}).catch(() => {this.$message({type: "info",message: "已取消删除",});});},},

是参照这位博主的改进的  仅作为本人的学习积累笔记  如有侵权 私信我删除谢谢vue+element实现图片上传及裁剪功能(vue-cropper)_努力搬砖的阿一的博客-CSDN博客_element 图片裁切

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论