今天就跟大家聊聊有關Vue+Element-UI實現上傳圖片并壓縮,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
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 {
//壓縮質量
imgQuality: 0.5,
imageUrl: ''
}
methods: {
handleAvatarSuccess(res, file) {
// 服務器返回結果處理
},
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);
})
}
}看完上述內容,你們對Vue+Element-UI實現上傳圖片并壓縮有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。