h5上传图片及预览

时间:2023-03-09 04:01:14
h5上传图片及预览

第一次做图片上传,记录一些问题。

1,图片的base64编码就是可以将一副图片数据编码成一串字符串,使用该字符串代替图像地址。而网页上的每一个图片,都是需要消耗一个http请求下载而来的,使用base64就不用请求http。

2,上传图片:

 <div id="ImgPr"></div>
<input class="click-upload" type="file" id="up" accept="image/*">

   3,图片转base64(readAsDataURL方法用于读取指定Blob或File的内容。当读操作完成,readyState变为DONE, loadend被触发,此时result属性包含数据:URL以base64编码的字符串表示文件的数据):

 function picUpload() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}

4,压缩图片并转base64(通过canvas把图片进行大小压缩):

 function picUpload(){
var me=this;
var img = new Image();
$('#up').on('change',function(){
var ViewWidth=$(this).width();
var ViewHeight=$(this).height();
var file = this.files[0];
var URL = URL || webkitURL;
img.src=URL.createObjectURL(file);
img.onload = function(){
var imgMe=this,
imgWidth=0,
imgHeight= 0,
w = imgMe.width,
h = imgMe.height,
scale1 = w/ViewWidth,
scale2 = h/ViewHeight;
imgWidth=parseInt(Math.floor(w/scale1));
imgHeight=parseInt(Math.floor(h/scale2));
var canvas = document.createElement('canvas');
var img = document.createElement('img');
$('#ImgPr').html(img);
var ctx = canvas.getContext('2d');
canvas.width = ViewWidth;
canvas.height = ViewHeight;
ctx.drawImage(imgMe,0,0,imgWidth,imgHeight);
me.src=canvas.toDataURL('image/jpeg');
$(img).prop("src",me.src);
};
});
};

  5,$.ajax()方法里的data如果是字符串则不能用大括号括起来,这样在有某些手机上会报错。