Vue+Element-UI實(shí)現(xiàn)上傳圖片并壓縮
Vue+Element-UI 上傳圖片并壓縮,供大家參考,具體內(nèi)容如下
1.版本
Vue:2.5.2
Element-UI:2.12.0
可實(shí)現(xiàn)圖片上傳前,自動(dòng)壓縮。
Element-UI組件,詳情見(jiàn) 官網(wǎng)。
2.template部分
<el-form-item label="照片"> <el-upload accept="image/*" class="avatar-uploader" :action="uploadPath" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imgUrl" :src="imgUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item>
3.script部分
data() {
return {
//壓縮質(zhì)量
imgQuality: 0.5,
imageUrl: ''
}
methods: {
handleAvatarSuccess(res, file) {
// 服務(wù)器返回結(jié)果處理
},
dataURItoBlob(dataURI, type) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: type});
},
beforeAvatarUpload(file) {
const _this = this
return new Promise(resolve => {
const reader = new FileReader()
const image = new Image()
image.onload = (imageEvent) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const width = image.width * _this.imgQuality
const height = image.height * _this.imgQuality
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
const dataUrl = canvas.toDataURL(file.type);
const blobData = _this.dataURItoBlob(dataUrl, file.type);
resolve(blobData)
}
reader.onload = (e => { image.src = e.target.result; });
reader.readAsDataURL(file);
})
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue2中使用自定義指令實(shí)現(xiàn)el-table虛擬列表的代碼示例
在實(shí)際開(kāi)發(fā)中,我們可能會(huì)面臨其他需求,例如在 el-table 中無(wú)法使用分頁(yè)技術(shù)的情況下展示海量數(shù)據(jù),這種情況下,頁(yè)面可能會(huì)出現(xiàn)卡頓,嚴(yán)重時(shí)甚至可能引發(fā)瀏覽器崩潰,所以針對(duì)這個(gè)問(wèn)題本文給大家介紹了vue2中使用自定義指令實(shí)現(xiàn)el-table虛擬列表,需要的朋友可以參考下2025-01-01
vue2前端調(diào)用WebSocket有消息進(jìn)行通知代碼示例
在Vue項(xiàng)目中實(shí)現(xiàn)全局的消息鏈接監(jiān)聽(tīng)主要涉及到了WebSocket技術(shù),這是一種雙向通信協(xié)議,允許客戶端與服務(wù)器之間實(shí)時(shí)、高效地交換數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于vue2前端調(diào)用WebSocket有消息進(jìn)行通知的相關(guān)資料,需要的朋友可以參考下2024-07-07
vue element table 表格請(qǐng)求后臺(tái)排序的方法
今天小編就為大家分享一篇vue element table 表格請(qǐng)求后臺(tái)排序的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
vue-router中的hash和history兩種模式的區(qū)別
大家都知道vue-router有兩種模式,hash模式和history模式,這里來(lái)談?wù)剉ue-router中的hash和history兩種模式的區(qū)別。感興趣的朋友一起看看吧2018-07-07
vue長(zhǎng)列表優(yōu)化之虛擬列表實(shí)現(xiàn)過(guò)程詳解
前端的業(yè)務(wù)開(kāi)發(fā)中會(huì)遇到不使用分頁(yè)方式來(lái)加載長(zhǎng)列表的需求,下面這篇文章主要給大家介紹了關(guān)于vue長(zhǎng)列表優(yōu)化之虛擬列表實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
vue子路由跳轉(zhuǎn)實(shí)現(xiàn)tab選項(xiàng)卡
這篇文章主要為大家詳細(xì)介紹了vue子路由跳轉(zhuǎn)實(shí)現(xiàn)tab選項(xiàng)卡,完成一個(gè)簡(jiǎn)單的tab選項(xiàng)卡布局,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07

