0

基于HTML5的多张图片上传带预览

点击选择图片(可选多张),确定后可以在页面上预览选择的图片,点击提交将图片提交给后台。

主要的逻辑过程就是:
1.用input标签并选择type=file,记得带上multiple,不然就只能单选图片了

2.绑定好input的change时间,

3.处理change事件,注意:此处是重点,change事件中包含两个操作:a.根据图片宽高比,显示自适应图片,b.将使用H5新的FileReader接口读取文件并生成对应的base64编码

最后一件事情,就是将图片上传到你们自己的服务器,交给后台开发人员去完成好了。

废话不多少,直接上代码,代码中会有详细的注释说明:

<!DOCTYPE html>    
<html>    
<head>    
<meta charset="UTF-8">    
<title>showImages</title>    
<style type="text/css">   
.float{    
    float:left;    
    width : 200px;    
    height: 200px;    
    overflow: hidden;    
    border: 1px solid #CCCCCC;    
    border-radius: 10px;    
    padding: 5px;    
    margin: 5px;    
}    
img{position: relative;}    
.result{    
    width: 200px;    
    height: 200px;    
    text-align: center;    
    box-sizing: border-box;    
}   

#file_input{display: none;}  

.delete{  
    width: 200px;  
    height:200px;  
    position: absolute;  
    text-align: center;  
    line-height: 200px;  
    z-index: 10;  
    font-size: 30px;  
    background-color: rgba(255,255,255,0.8);  
    color: #777;  
    opacity: 0;  
    transition-duration: :0.7s;  
    -webkit-transition-duration: 0.7s;   
}  

.delete:hover{  
    cursor: pointer;  
    opacity: 1;  
}  
</style>    
    
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>    
<script type="text/javascript">    
window.onload = function(){    
    var input = document.getElementById("file_input");    
    var result;    
    var imageArray = []; // 储存所选图片的结果(文件名和base64数据)  
    var fd;  //FormData方式发送请求    
    var oSelect = document.getElementById("select");  
    var oAdd = document.getElementById("add");  
    var oSubmit = document.getElementById("submit");  
    var oInput = document.getElementById("file_input");  
     
    if(typeof FileReader==='undefined'){    
        alert("Sorry,你的浏览器不支持 FileReader");    
        input.setAttribute('disabled','disabled');    
    }else{
        //添加change监听事件,当选择文件后,自动调用readFile方法,读取并显示选择的图片
        input.addEventListener('change',readFile,false);    
    }     //handler    
    
    function readFile(){   
        fd = new FormData();    
        var iLen = this.files.length;  
        var index = 0;  
        for(var i=0;i<iLen;i++){  
            if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){  //判断上传文件格式    
                return alert("上传的图片格式不正确,请重新选择");    
            }  
            var reader = new FileReader();  
            reader.index = i;    
            fd.append(i,this.files[i]);  
            reader.readAsDataURL(this.files[i]);  //转成base64    
            reader.fileName = this.files[i].name;  
  
  
            reader.onload = function(e){   
                var imgMsg = {    
                    name : this.fileName,    //获取文件名    
                    base64 : this.result    //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里    
                }   
                imageArray.push(imgMsg);    
                //自动在每个图片上面,加上一个delete按钮,当鼠标位于图片上面时,自动显示。
                result = '<div class="delete">delete</div><div class="result"><img src="'+this.result+'" alt=""/></div>';    
                var div = document.createElement('div');  
                div.innerHTML = result;    
                div['className'] = 'float';  
                div['index'] = index;    
                document.getElementsByTagName('body')[0].appendChild(div);    //插入dom树    
                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';    
                    }    
                }   
  
                  //点击delete按钮,删除指定的图片
                div.onclick = function(){  
                    this.remove();               // 在页面中删除该图片  
                    delete imageArray[this.index];  // 在数组imageArray中删除对应的数据  
                }  
                index++;  
            }    
        }    
    }    
        
    //上传图片数据到服务器
    function send(){   
        var submitArr = [];  
        for (var i = 0; i < imageArray.length; i++) {  
            if (imageArray[i]) {  
                submitArr.push(imageArray[i]);  
            }  
        }  
        // console.log('提交的数据:'+JSON.stringify(submitArr)) 
        $.ajax({    
            url : 'http://www.jbsage.com/',    //这里提花昵称你要提交的服务器地址
            type : 'post', 
            data : JSON.stringify(submitArr),    
            dataType: 'json',    
            //processData: false,   用FormData传fd时需有这两项    
            //contentType: false,    
            success : function(data){    
                console.log('返回的数据:'+JSON.stringify(data))    
           }
 
        })    
    }    
    //【重新-选择图片】方法调用
    oSelect.onclick=function(){   
        oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发  
        //清空已选图片  
        $('.float').remove();  
        imageArray = [];   
        index = 0;          
        oInput.click();   
    }   
    //【追加-图片】方法调用
    oAdd.onclick=function(){  
        oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发  
        oInput.click();   
    }   
       //上传图片数据之前,要判断是否选择有文件
    oSubmit.onclick=function(){    
        if(!imageArray.length){    
            return alert('请先选择文件');    
        }    
        send();    
    }    
}    
/*    
 用ajax发送fd参数时要告诉jQuery不要去处理发送的数据,    
 不要去设置Content-Type请求头才可以发送成功,否则会报“Illegal invocation”的错误,    
 也就是非法调用,所以要加上“processData: false,contentType: false,”    
 * */    
    
                
function ReSizePic(thePicture) {    
    var RePicWidth = 200; //这里修改为想要显示的宽度值    
    
    var TrueWidth = thePicture.width;      //图片显示宽度    
    var TrueHeight = thePicture.height;  //图片显示高度    
    //根据宽、高计算出图片应该显示的正常比例
    if(TrueWidth>TrueHeight){    
        //宽大于高    
        var reWidth = RePicWidth;    
        thePicture.width = reWidth;    
        //垂直居中    
        var nowHeight = TrueHeight * (reWidth/TrueWidth);    
        return nowHeight;  //将图片修改后的高度返回,供垂直居中用    
    }else{    
        //宽小于高    
        var reHeight = RePicWidth;    
        thePicture.height = reHeight;    
    }    
}    
    
       
</script>    
</head>    
<body>    
    <div class="container">    
        <label>请选择图像文件:</label>  
        <button id="select">重新-选择图片</button>  
        <button id="add">追加-图片</button>  
        <input type="file" id="file_input" multiple/> <!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->    
        <button id="submit">上传</button>
    </div>    
</body>    
</html>


以上代码已经过测试,运行环境:DreamWeaver 2015、Chrome  67.0.3396.99(正式版本) (64 位)、 Mac OS Sierra 10.12.4。
提示:代码可正常执行,如不能执行,纯属意外。