公共组件:

<template>
<div>
<div class="upload-box">
<div class="image-box"
v-if="imageUrl"
:style="{'background-image': 'url('+ imageUrl +')', 'height': imageHeight}"></div>
<div class="upload">
<h6 class="upload-des">支持 jpg、png 格式大小 5M 以内的图片</h6>
<input type="file" @change="getFile" ref="file" id="file">
<label for="file">点击上传</label>
</div>
</div>
<!-- vueCropper 剪裁图片实现-->
<div class="vue-cropper-box" v-if="isShowCropper">
<div class="vue-cropper-content">
<vueCropper ref="cropper"
:img="option.img"
:outputSize="option.outputSize"
:outputType="option.outputType"
:info="option.info"
:canScale="option.canScale"
:autoCrop="option.autoCrop"
:autoCropWidth="option.autoCropWidth"
:autoCropHeight="option.autoCropHeight"
:fixed="option.fixed"
:fixedNumber="option.fixedNumber">
</vueCropper>
</div>
</div>
<el-button v-if="isShowCropper" type="danger" @click="onCubeImg">确定裁剪图片</el-button>
</div>
</template>
<script>
import VueCropper from "vue-cropper"
export default {
name: 'Avatar', data () {
return {
//裁剪组件的基础配置option
option: {
img: '', //裁剪图片的地址
info: true, //裁剪框的大小信息
outputSize: , // 裁剪生成图片的质量
outputType: 'png', //裁剪生成图片的格式
canScale: false, // 图片是否允许滚轮缩放
autoCrop: true, // 是否默认生成截图框
autoCropWidth: , // 默认生成截图框宽度
autoCropHeight: , // 默认生成截图框高度
fixed: false, //是否开启截图框宽高固定比例
fixedNumber: [, ] //截图框的宽高比例
},
isShowCropper: false //是否显示截图框
}
}, props: {
// 特殊配置
cropperOption: {
type: Object,
default: () => {
return null
}
},
// 默认图片
imageUrl: {
type: String,
default: ''
},
// 图片展示高度
imageHeight: {
type: String,
default: '100px'
}
}, components: {
VueCropper
}, methods: {
getFile (e) {
let _this = this
var files = e.target.files[]
if (!e || !window.FileReader) return // 看支持不支持FileReader
let reader = new FileReader()
reader.readAsDataURL(files)
reader.onloadend = function () {
_this.isShowCropper = true
_this.option.img = this.result
_this.$refs.file.value = ''
}
}, // 确定裁剪图片
onCubeImg () {
this.$refs.cropper.getCropData((data) => {
this.isShowCropper = false
//console.log("压缩前的图片大小:" + data.length)
let img = new Image(),
_this = this
img.src = data
img.onload = function() {
//let _data = _this.compress(img)
let blob = _this.dataURItoBlob(data) let formData = new FormData()
formData.append("icon", blob)
//console.log("将blob对象转成formData对象:" + formData.get("icon"))
_this.$emit('cropped', data, formData)
}
})
}, // 压缩图片
compress(img) {
let canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
initSize = img.src.length,
width = img.width,
height = img.height;
canvas.width = width
canvas.height = height
// 铺底色
ctx.fillStyle = "#fff"
ctx.fillRect(, , canvas.width, canvas.height)
ctx.drawImage(img, , , width, height)
//进行压缩
let ndata = canvas.toDataURL("image/jpeg", 0.8)
//console.log("压缩后的图片大小:" + ndata.length)
return ndata
},
// base64转成bolb对象
dataURItoBlob(base64Data) {
let byteString
if (base64Data.split(",")[].indexOf("base64") >= )
byteString = atob(base64Data.split(",")[])
else
byteString = unescape(base64Data.split(",")[])
let mimeString = base64Data .split(",")[] .split(":")[] .split(";")[];
let ia = new Uint8Array(byteString.length);
for (let i = ; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString })
}, // 初始化配置文件
initOptions () {
this.isShowCropper = false
if (this.cropperOption) {
for (let key in this.option) {
this.option[key] = this.cropperOption[key] || this.option[key]
}
}
}
}, created () {
this.initOptions()
}
}
</script>
<style scoped lang="stylus" rel="stylesheet">
.upload-box {
& > div {
display inline-block
vertical-align middle
}
& .upload-des {
margin
font-weight
color #
}
} .image-box {
width 100px
height 100px
margin-right 20px
background-size 100px auto
background-position left center
background-repeat no-repeat
} .upload {
& label {
width: 80px;
height: 24px;
font-size: 12px;
line-height: 24px;
display: inline-block;
border-radius: 4px;
text-align: center;
border: 1px solid #ddd;
cursor pointer
}
} input[type='file'] {
display: none;
} .vue-cropper-box {
width: %;
height: 200px;
margin: 15px 0px;
.vue-cropper-content {
height 200px
}
}
</style>

  调用

<el-form-item label="头像" prop="icon" :rules="rules.required">
  <Avatar v-on:cropped="doCrop"
  :cropperOption="cropperOption"
  :imageUrl="guestInfo.icon"></Avatar>
</el-form-item>

  注意下面这个二进制文件接收和上传的问题

resetForm(){
  this.$nextTick(() => {
    this.$refs.guest.clearValidate()
    this.guestUpInfo = new FormData()
  })
},
//完成裁剪
doCrop(icon, file){
  this.guestInfo.icon = icon
  this.guestUpInfo = file
}
//新增、编辑提交
submitGuest(){
validCallback(this, 'guest', () => {
this.guestUpInfo.append('name',this.guestInfo.name)
this.guestUpInfo.append('position',this.guestInfo.position)
this.guestUpInfo.append('description',this.guestInfo.description)
if(this.guestInfo.seq){
this.guestUpInfo.append('seq',this.guestInfo.seq)
}
if(this.editGuest){
this.guestUpInfo.append('id',this.guestInfo.id)
} publicSubmitApi('saveSpeaker', this.guestUpInfo, true).then(res => {
if (res.status === ) {
this.guestShow = false
this.fetchData()
this.$message({
message: this.editGuest ? '编辑成功' : '新增成功',
type: 'success'
})
}
})
})
},

利用vue-cropper做的关于图片裁剪、压缩、上传、预览等做的一个公共组件的更多相关文章

  1. js实现本地的图片压缩上传预览

    js在设计时考虑到安全的原因是不允许读写本地文件的,随着html5的出现提供了fileReader AP从而可以I实现本地图片的读取预览功能, 另外在移动端有的限制图片大小的需求,主要是考虑图片过大会 ...

  2. jQuery插件ImgAreaSelect 实例讲解一(头像上传预览和裁剪功能)

    上一节随笔中,我们已经知道了关于jQuery插件ImgAreaSelect基本的知识:那么现在看一下实例: 首先,要知道我们应该实现什么功能? (1)图片能够实现上传预览功能 (2)拖拽裁剪图片,使其 ...

  3. [前端 4] 使用Js实现图片上传预览

    导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...

  4. js实现图片上传预览及进度条

    原文js实现图片上传预览及进度条 最近在做图片上传的时候,由于产品设计的比较fashion,上网找了比较久还没有现成的,因此自己做了一个,实现的功能如下: 1:去除浏览器<input type= ...

  5. 模拟QQ心情图片上传预览

    出于安全性能的考虑,目前js端不支持获取本地图片进行预览,正好在做一款类似于QQ心情的发布框,找了不少jquery插件,没几个能满足需求,因此自己使用SWFuplad来实现这个图片上传预览. 先粘上以 ...

  6. 微信开发中使用微信JSSDK和使用URL.createObjectURL上传预览图片的不同处理对比

    在做微信公众号或者企业微信开发业务应用的时候,我们常常会涉及到图片预览.上传等的处理,往往业务需求不止一张图片,因此相对来说,需要考虑的全面一些,用户还需要对图片进行预览和相应的处理,在开始的时候我使 ...

  7. ASP.NET工作笔记之一:图片上传预览及无刷新上传

    转自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.html 最近项目里面涉及到无刷新上传图片的功能,其实也就是上 ...

  8. 用html5文件api实现移动端图片上传&预览效果

    想要用h5在移动端实现图片上传&预览效果,首先要了解html5的文件api相关知识(所有api只列举本功能所需): 1.Blob对象  Blob表示原始二进制数据,Html5的file对象就继 ...

  9. signup图片上传预览经常总结

    html <html> <head> <meta charset="utf-8" /> <meta http-equiv="X- ...

  10. 图片上传预览转压缩并转base64详解(dShowImg64.js)

    hello,大家好,游戏开始了,欢迎大家收看这一期的讲解.本次的内容是图片的上传预览.最后发源码链接.废话不多说,先上图. 待上传图像 点击蓝色框内,pc可以选择文件,移动端选择拍照或选择图片进行上传 ...

随机推荐

  1. hdu CA Loves GCD(dp)

    一道我想骂人的题,差点把我气炸了. 题意: 求一个数的集合中(非多重集,每个数只出现一次)所有子集的gcd的和.结果MOD10^8+7输出. 输入输出不说了,自己看吧,不想写了. 当时我真把它当作数论 ...

  2. [USACO08OCT]Watering Hole

    [USACO08OCT]Watering Hole 题目大意: Farmer John 有\(n(n\le300)\)个牧场,他希望灌溉他的所有牧场.牧场编号为\(1\sim n\),要灌溉一个牧场有 ...

  3. BZOJ1768 : [Ceoi2009]logs

    从上到下枚举行,可以$O(m)$更新现在每一列往上连续的1的个数,也可以在$O(m)$的时间内完成排序.总复杂度$O(nm)$. #include<cstdio> #define M 15 ...

  4. hdu 5761 Rower Bo 物理题

    Rower Bo 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5761 Description There is a river on the Ca ...

  5. OpenVPN搭建中tap与tun的实际使用区别

    tap俗称网桥模式,tun俗称路由模式,tap在二层,tun在三层,在实际应用中,其实以上这些知识概念,我是抄来的,具体的解释可以看以下参考链接. 下面将介绍在实际使用中的区别: 1.tap可以直接使 ...

  6. Ubuntu 16.04实现SSH无密码登录/免密登录/自动登录(ssh-keygen/ssh-copy-id)

    ssh-keygen:产生公钥与私钥(在~/.ssh) ssh-copy-id:将本机的公钥复制到远程机器的authorized_keys文件中(在~/.ssh),ssh-copy-id也能让你有到远 ...

  7. 汽车之家店铺数据抓取 DotnetSpider实战

    一.背景 春节也不能闲着,一直想学一下爬虫怎么玩,网上搜了一大堆,大多都是Python的,大家也比较活跃,文章也比较多,找了一圈,发现园子里面有个大神开发了一个DotNetSpider的开源库,很值得 ...

  8. 在centos中安装jenkins master为service

    需要sudo或root权限.    翻译自: https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Red+Hat+dis ...

  9. 有谁知道Delphi中"窗口"的创建过程?

      求助:有谁知道Delphi中窗口的创建过程,此“窗口”不仅仅指 TForm 类型, 还包括一般的窗口控件,如TButton,TEdit等等,希望有能够十分详细的运作 过程,比如说CreatPara ...

  10. 清除数据库表、外键、存储过程SQL

    1.删除所有外键 )    begin         exec(@c1)        fetchnextfrom c1 into@c1    endclose c1deallocate c1 2. ...