前台獲取並限制上傳文件大小、上傳文件格式


        <input type="file" id="file"/>
        <input type="button" id="btn" value="js查看文件大小"/>
        <input type="button" id="btn1" value="jq查看文件大小"/>
        <script>
            //js獲取上傳文件大小(單位:字節)
 document.getElementById("btn").onclick=function(){ alert(document.getElementById("file").files[0].size); }; //jq獲取上傳文件大小(單位:字節) jq轉js,加下標即可
 $("#btn1").click(function(){ alert($("#file")[0].files[0].size); }); </script>

 

        <div id="fileparent"><input type="file" id="file"/></div>
        <input type="button" id="btn" value="js查看文件大小"/>
        <input type="button" id="btn1" value="jq查看文件大小"/>
        <script>
            //js獲取上傳文件大小(單位:字節)
 document.getElementById("btn").onclick=function(){ alert(document.getElementById("file").files[0].size); }; //限制上傳文件大小(單位:字節) 
            //限制上傳文件格式,可直接判斷后綴或者用indexOf方法判斷后綴格式是否符合要求
 $("#btn1").click(function(){ alert($("#file")[0].files[0].size); if($("#file")[0].files[0].size>1024000){ alert("文件過大!"); //清理file里的文件內容
 $("#fileparent").html('<input type="file" id="file"/>'); return; } alert($("#file").val()); //獲取上傳文件路徑
                var string=$("#file")[0].value; //對路徑字符串進行剪切截取
                var arrays=string.split("\\"); //獲取文件名,包含后綴
                var name=arrays[arrays.length-1]; alert(name); //為了辨別格式,統一變小寫
 name=name.toLowerCase(); if(!(name.endsWith("png")||name.endsWith("jpg")||name.endsWith("jpeg"))){ alert("請上傳jpg、jpeg或png格式的圖片!"); //清理file里的文件內容
 $("#fileparent").html('<input type="file" id="file"/>'); } });  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM