天天看點

JQuery多圖檔上傳預覽JQuery多圖檔上傳+預覽

JQuery多圖檔上傳+預覽

參考自

這是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;  
    }  
           

這是body部分

<div class="container">    
       <label>圖檔選擇:</label>  
       <button id="select">更換圖檔</button>  
       <button id="add">追加圖檔</button>  
       <input type="file" id="file_input" multiple/> <!--multiple是多選的關鍵-->    
       <button id="submit">送出</button>
 </div>    
  <div class="get"></div>
           

這是引入的依賴

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>  
           

這是js部分

$(function(){ 
    var input = $("#file_input");    
    var result;    
    var dataArr = []; // 儲存所選圖檔的結果(檔案名和base64資料)  
    var fd;  //FormData方式發送請求    
    var oSelect = $("#select");  
    var oAdd = $("#add");  
    var oSubmit = $("#submit");  
    var oInput = $("#file_input");  
     
    if(typeof FileReader==='undefined'){    
        alert("抱歉,你的浏覽器不支援 FileReader");    
       input.setAttribute('disabled','disabled');    
    }else{    
        $("#file_input").on('change',readFile);   
    }     //handler    
    
        
    function readFile(){   
        fd = new FormData();    
        var iLen = this.files.length; 
        var path=$("#file_input").val();
        var extStart =path.lastIndexOf('.');
        var ext = path.substring(extStart,path.length).toUpperCase(); 
        for(var i=0;i<iLen;i++){  
            if (ext !== '.PNG' && ext !== '.JPG' && ext !== '.JPEG' && ext !== '.GIF'){  //判斷上傳檔案格式    
                return alert("上傳的圖檔格式不正确,請重新選擇");    
            }  
            var reader = new FileReader();  
            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裡    
                }   
                dataArr.push(imgMsg);    
                result = '<div class="delete">删除</div><div class="result"><img class="subPic" src="'+this.result+'" alt="'+this.fileName+'"/></div>';    
                var div = document.createElement('div');  
                div.innerHTML = result;    
                div['className'] = 'float';  
                $(".get")[0].append(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';    
                    }    
                }   
                div.onclick = function(){  
                    $(this).remove();                  // 在頁面中删除該圖檔元素  
                }  
            }    
        }    
    }    
        
        
    function send(){   
        var submitArr = [];  
        $('.subPic').each(function () {
                submitArr.push({
                    name: $(this).attr('alt'),
                    base64: $(this).attr('src')
                });  
            }
        );
        $.ajax({    
            url : 'http://123.206.89.242:9999',    
            type : 'post', 
            data : JSON.stringify(submitArr),    
            dataType: 'json',    
            //processData: false,   用FormData傳fd時需有這兩項    
            //contentType: false,    
            success : function(data){    
                console.log('傳回的資料:'+JSON.stringify(data))    
           }
        })    
    }    
        
     
  
  $("#select").click(function(){
    oInput.value = "";   // 先将oInput值清空,否則選擇圖檔與上次相同時change事件不會觸發  
        //清空已選圖檔  
        $('.float').remove();        
        oInput.click(); 
  })
  $("#add").click(function(){
        oInput.value = "";   // 先将oInput值清空,否則選擇圖檔與上次相同時change事件不會觸發  
        oInput.click();   
  })
  
    $("#submit").click(function(){
        if(!dataArr.length){    
            return alert('請先選擇檔案');    
        }    
        send();   
    })
  
  
} )     
             
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;    
    }    
}    
           

接下來是全部的代碼

<!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>    
    
    
   
</head>    
    <body>    
            <div class="container">    
                <label>添加圖檔:</label>  
                <button id="select">更新圖檔</button>  
                <button id="add">繼續添加</button>  
                <input type="file" id="file_input" multiple/> 
                <button id="submit">送出</button>
            </div>    
            <div class="get"></div>
    </body>  
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>    
<script type="text/javascript">    
    
    
$(function(){   
    var result;    
    var dataArr = []; // 儲存所選圖檔的結果(檔案名和base64資料)  
    var fd;  //FormData方式發送請求    
    var oInput = $("#file_input");  
     
    if(typeof FileReader==='undefined'){    
        alert("抱歉,你的浏覽器不支援 FileReader");    
       input.setAttribute('disabled','disabled');    
    }else{    
        $("#file_input").on('change',readFile);   
    }     //handler    
    
        
    function readFile(){   
        fd = new FormData();    
        var iLen = this.files.length; 
        var path=$("#file_input").val();
        var extStart =path.lastIndexOf('.');
        var ext = path.substring(extStart,path.length).toUpperCase(); 
        for(var i=0;i<iLen;i++){  
            if (ext !== '.PNG' && ext !== '.JPG' && ext !== '.JPEG' && ext !== '.GIF'){  //判斷上傳檔案格式    
                return alert("上傳的圖檔格式不正确,請重新選擇");    
            }  
            var reader = new FileReader();  
            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裡    
                }   
                dataArr.push(imgMsg);    
                result = '<div class="delete">删除</div><div class="result"><img class="subPic" src="'+this.result+'" alt="'+this.fileName+'"/></div>';    
                var div = document.createElement('div');  
                div.innerHTML = result;    
                div['className'] = 'float';  
                $(".get")[0].append(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';    
                    }    
                }   
                div.onclick = function(){  
                    $(this).remove();                  // 在頁面中删除該圖檔元素  
                }  
            }    
        }    
    }    
        
        
    function send(){   
        var submitArr = [];  
        $('.subPic').each(function () {
                submitArr.push({
                    name: $(this).attr('alt'),
                    base64: $(this).attr('src')
                });  
            }
        );
        $.ajax({    
            url : 'http://123.206.89.242:9999',    
            type : 'post', 
            data : JSON.stringify(submitArr),    
            dataType: 'json',    
            //processData: false,   用FormData傳fd時需有這兩項    
            //contentType: false,    
            success : function(data){    
                console.log('傳回的資料:'+JSON.stringify(data))    
           }
        })    
    }    
        
     
  
  $("#select").click(function(){
    oInput.value = "";   // 先将oInput值清空,否則選擇圖檔與上次相同時change事件不會觸發  
        //清空已選圖檔  
        $('.float').remove();        
        oInput.click(); 
  })
  $("#add").click(function(){
        oInput.value = "";   // 先将oInput值清空,否則選擇圖檔與上次相同時change事件不會觸發  
        oInput.click();   
  })
  
    $("#submit").click(function(){
        if(!dataArr.length){    
            return alert('請先選擇檔案');    
        }    
        send();   
    })
  
  
} )   
        
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;    
    }    
}    
 
    
                
</script>   
</html> 
           

寫的第一條部落格,謝謝支援