html5选择多张图片在页面内预览并上传到后台

需求:点击选择图片(可选多张),确定后将选择的图片显示在页面上,点击提交将图片提交给后台。

效果图:

html5选择多张图片在页面内预览并上传到后台_第1张图片

 

 

 

			    
			     
			    

 

html内容,主要是multiple属性,支持选择多个文件。是HTML5属性,注意兼容问题(IOS支持,安卓不支持)。

 

 

js内容:

 

    function readFile(){
    		dataArr = { data : [] };
    		fd = new FormData();
    		var iLen = this.files.length;
        	for(var i=0;i
'; div = document.createElement('div'); div.innerHTML = result; div['className'] = 'float'; document.getElementsByTagName('body')[0].appendChild(div);   //插入页面 var img = div.getElementsByTagName('img')[0]; img.onload = function(){ var nowHeight = ReSizePic(this); //设置图片大小 this.parentNode.style.display = 'block'; var oParent = this.parentNode; if(nowHeight){ oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px'; } } } } }


以上函数实现选择图片并显示在桌面上,其中img.onload的作用是将选中的图片进行缩放,放在宽高相等的div中并居中显示,可根据自己需求删除这句。

 

下面附上ReSizePic函数

 

function ReSizePic(ThisPic) {
	var RePicWidth = 200; //这里修改为您想显示的宽度值

	var TrueWidth = ThisPic.width; //图片实际宽度
	var TrueHeight = ThisPic.height; //图片实际高度
	
	if(TrueWidth>TrueHeight){
		//宽大于高
		var reWidth = RePicWidth;
		ThisPic.width = reWidth;
		//垂直居中
		var nowHeight = TrueHeight * (reWidth/TrueWidth);
		return nowHeight;  //将图片修改后的高度返回,供垂直居中用
	}else{
		//宽小于高
		var reHeight = RePicWidth;
		ThisPic.height = reHeight;
	}
}

 

 

 

 

 

以上就实现了图片选择展示,并将所选图片转成base64保存在dataArr中,之后用ajax上传即可。

 

    function send(){
   		$.ajax({
            url : 'http://...',
            type : 'post',
            data : dataArr,
            dataType: 'json',
            //processData: false,   用FormData传fd时需有这两项
            //contentType: false,
            success : function(data){
                console.log('返回的数据:'+JSON.stringify(data))
           } 
        })
   	}
    
    var oBtn = document.getElementsByTagName('button')[0];
    oBtn.onclick = function(){
    		if(!input.files.length){
    			return alert('请先选择文件');
    		}
  		send();
    }

 

 

 

 

 

至于用FormData上传,方法大同小异,这里不再演示了。

 

下面是完整代码

 






showImages






    
            

 

 

 

 

你可能感兴趣的:(HTML5)