本文實(shí)例為大家分享了vue實(shí)現(xiàn)壓縮圖片預(yù)覽并上傳的具體代碼,供大家參考,具體內(nèi)容如下
主要用到filereader、canvas 以及 formdata 這三個(gè)h5的api
過程大致分為三步:
用戶使用input file上傳圖片的時(shí)候,用filereader讀取用戶上傳的圖片數(shù)據(jù)(base64格式)
把圖片數(shù)據(jù)傳入img對象,然后將img繪制到canvas上,再調(diào)用canvas.toDataURL對圖片進(jìn)行壓縮
獲取到壓縮后的base64格式圖片數(shù)據(jù),轉(zhuǎn)成二進(jìn)制塞入formdata,再通過XmlHttpRequest提交formdata。
模板:
<template> <div class="image-box"> <input type="file" accept="image/*" @change="imageHandle"> <img ref="upImg"/> </div></template>
獲取圖片數(shù)據(jù)
methods: { //監(jiān)聽input file的change事件 imageHandle(e) { //**這個(gè)是必不可少的,在下面的reader.onload中this就不再指vm了** let that = this; let maxSize = 100 * 1024; let files = e.srcElement.files; if (!files.length) return; //文件長度大于0 if (!/^image///.test(files[0].type)) return; //必須是圖片才處理 if (!window.FileReader) return; //支持FileReader //創(chuàng)建filereader對象 let reader = new FileReader(); reader.readAsDataURL(files[0]); //將圖片轉(zhuǎn)成base64格式 reader.onload = function() { let result = this.result; let img = new Image(); img.src = result; let formdata = new FormData(); if (this.result.length <= maxSize) { that.$refs.upImg.src = result; //預(yù)覽圖片 img = null; //上傳圖片 formdata.append("image", that._upload(result, files[0].name, files[0].type)); that.$store.dispatch("uploadImage", formdata) .then(data => { if (data === 1) { that.$toast("上傳成功", "success"); } else if (data === -1) { that.$toast("圖片為空", "error"); } else { that.$toast("上傳失敗", "error"); } }) .catch(error => that.$toast("上傳失敗", "error")); } else { img.onload = function() { //壓縮圖片 let data = that._compress(img); //圖片預(yù)覽 that.$refs.upImg.src = data; //上傳圖片 formdata.append("image", that._upload(data, files[0].name, files[0].type)); that.$store.dispatch("uploadImage", formdata) .then(data => { if (data === 1) { that.$toast("上傳成功", "success"); } else if (data === -1) { that.$toast("圖片為空", "error"); } else { that.$toast("上傳失敗", "error"); } }) .catch(error => that.$toast("上傳失敗", "error")); }; } }; },壓縮圖片
在IOS中,canvas繪制圖片是有兩個(gè)限制的:
首先是圖片的大小,如果圖片的大小超過兩百萬像素,圖片也是無法繪制到canvas上的,調(diào)用drawImage的時(shí)候不會報(bào)錯(cuò),但是你用toDataURL獲取圖片數(shù)據(jù)的時(shí)候獲取到的是空的圖片數(shù)據(jù)。
新聞熱點(diǎn)
疑難解答
圖片精選