h5上传图片及预览
? ? 第一次做圖片上傳,記錄一些問題。
? ? 1,圖片的base64編碼就是可以將一副圖片數(shù)據(jù)編碼成一串字符串,使用該字符串代替圖像地址。而網(wǎng)頁上的每一個圖片,都是需要消耗一個http請求下載而來的,使用base64就不用請求http。
? ? 2,上傳圖片:
1 <div id="ImgPr"></div> 2 <input class="click-upload" type="file" id="up" accept="image/*">?3,圖片轉(zhuǎn)base64(readAsDataURL方法用于讀取指定Blob或File的內(nèi)容。當讀操作完成,readyState變?yōu)镈ONE, loadend被觸發(fā),此時result屬性包含數(shù)據(jù):URL以base64編碼的字符串表示文件的數(shù)據(jù)):
1 function picUpload() { 2 var preview = document.querySelector('img'); 3 var file = document.querySelector('input[type=file]').files[0]; 4 var reader = new FileReader(); 5 reader.onloadend = function () { 6 preview.src = reader.result; 7 } 8 if (file) { 9 reader.readAsDataURL(file); 10 } else { 11 preview.src = ""; 12 } 13 }? ? ?4,壓縮圖片并轉(zhuǎn)base64(通過canvas把圖片進行大小壓縮):
1 function picUpload(){ 2 var me=this; 3 var img = new Image(); 4 $('#up').on('change',function(){ 5 var ViewWidth=$(this).width(); 6 var ViewHeight=$(this).height(); 7 var file = this.files[0]; 8 var URL = URL || webkitURL; 9 img.src=URL.createObjectURL(file); 10 img.onload = function(){ 11 var imgMe=this, 12 imgWidth=0, 13 imgHeight= 0, 14 w = imgMe.width, 15 h = imgMe.height, 16 scale1 = w/ViewWidth, 17 scale2 = h/ViewHeight; 18 imgWidth=parseInt(Math.floor(w/scale1)); 19 imgHeight=parseInt(Math.floor(h/scale2)); 20 var canvas = document.createElement('canvas'); 21 var img = document.createElement('img'); 22 $('#ImgPr').html(img); 23 var ctx = canvas.getContext('2d'); 24 canvas.width = ViewWidth; 25 canvas.height = ViewHeight; 26 ctx.drawImage(imgMe,0,0,imgWidth,imgHeight); 27 me.src=canvas.toDataURL('image/jpeg'); 28 $(img).prop("src",me.src); 29 }; 30 }); 31 };5,$.ajax()方法里的data如果是字符串則不能用大括號括起來,這樣在有某些手機上會報錯。
更多專業(yè)前端知識,請上 【猿2048】www.mk2048.com
總結(jié)
- 上一篇: js实现类名的添加与移除
- 下一篇: [JSON].typeOf( keyPa