公共组件:

<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. Cdq分治整体二分学习记录

    这点东西前前后后拖了好几个星期才学会……还是自己太菜啊. Cdq分治的思想是:把问题序列分割成左右两个,先单独处理左边,再处理左边对右边的影响,再单独处理右边.这样可以消去数据结构上的一个log,降低 ...

  2. NOIP2015其余几道题

    T1: #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> # ...

  3. [HDU4123]Bob’s Race

    题目大意:给定一棵$n$个点并且有边权的树,每个点的权值为该点能走的最远长度,并输入$m$个询问,每次询问最多有多少个编号连续的点,他们的最大最小点权差小于等于$Q$. 思路:两趟DP(DFS)求出每 ...

  4. BZOJ3501 : PA2008 Cliquers Strike Back

    \[\begin{eqnarray*}ans&=&m^{\sum_{i=1}^n Stirling2(n,i)\bmod 999999598}\bmod 999999599\\& ...

  5. STL中map的遍历

    map作为STL中的映射容器非常好用,我们来说一下map的遍历. map.first为key值,map.second为value值,key不可修改,value可修改. 定义一个迭代指针iter,使其指 ...

  6. CF330 C. Purification 认真想后就成水题了

    C. Purification time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...

  7. redis主从集群搭建及容灾部署(哨兵sentinel)

    Redis也用了一段时间了,记录一下相关集群搭建及配置详解,方便后续使用查阅. 提纲 Redis安装 整体架构 Redis主从结构搭建 Redis容灾部署(哨兵sentinel) Redis常见问题 ...

  8. Android Studio 怎样打JAR包

    Android Studio 怎样打JAR包 在eclipse中我们知道怎样将一个项目导出为jar包,供其他项目使用. 在AS中能够通过改动gradle才处理. 我们新建一个项目MakeJar,在项目 ...

  9. 委托、Lambda表达式、事件系列02,什么时候该用委托

    假设要找出整型集合中小于5的数. static void Main(string[] args) { IEnumerable<int> source = new List<int&g ...

  10. arcgis10.1安装出现1606错误怎么办?找不到盘符

    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ESRIHKEY_LOCAL_MACHINE\SOFTWARE\ESRIHKEY_CURRENT_USER\Softwa ...