# Jquery 顯示上傳檔案的容量大小 ```htmlembedded <tr> <th></font>附件上傳</th> <td colspan=3> <span style="font-weight: bold;">附加檔案1:</span> <s:file label="匯入" name="uploadFile" id="file1"/> <span id="file1Size"></span> <br> <span style="font-weight: bold;">附加檔案2:</span> <s:file label="匯入" name="uploadFile" id="file2"/> <span id="file2Size"></span> <br> <span style="font-weight: bold;">附加檔案3:</span> <s:file label="匯入" name="uploadFile" id="file3"/> <span id="file3Size"></span> <br> <p style="font-weight: bold;">總附件上傳檔案大小限制為10MB</p> </td> </tr> ``` ```javascript= function checkFile() { var fileSize= 0; var totalSize = 0 ; jQuery('input[name="uploadFile"]').each(function(i, item) { if(item.files.item(0) != null){ fileSize = item.files.item(0).size; $("#file"+(i+1)+"Size").text(calFileSize(fileSize)); totalSize = totalSize+fileSize ; } }); if(checkFileSize(totalSize)){ return true; }else{ return false; } } function calFileSize(fileSize){ if(fileSize<1024){ return "1KB"; }else if(fileSize<1048576){ return Math.ceil(fileSize/1024)+"KB"; }else{ return roundTo(fileSize/1048576,2)+"MB"; } } //取小數點n位四捨五入 function roundTo(num,decimal){ return Math.round( ( num + Number.EPSILON ) * Math.pow( 10, decimal ) ) / Math.pow( 10, decimal ); } //取小數點n位無條件進位 function roundUp(num,decimal){ return Math.ceil( ( num + Number.EPSILON ) * Math.pow( 10, decimal ) ) / Math.pow( 10, decimal ); } //檢查檔案大小 function checkFileSize(totalSize) { var SizeLimit = 1024*1024*10; //上傳上限(10MB),單位:byte if (totalSize > SizeLimit) { var msg = "附件已超過上傳上限 "+(SizeLimit /(1024*1024)) + " MB\n不允許上傳!"; alert(msg); return false; } else { return true; } } ``` ```javascript= $(document).ready(function(){ $("input[name=uploadFile]").change(function(){ checkFile(); }); }); ``` --- **最後成果:** ![](https://i.imgur.com/U6f4qP0.png) ###### tags: `javascript`