[轉貼]上傳檔案前,JavaScript檢查檔案格式、大小

來源:互聯網
上載者:User

資料來源:http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090219135915SXD&fumcde=

特別感謝Bryan大大的提供

範常式式如下:

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=big5"> <title>上傳</title> </head> <body> <form ACTION="upload.asp" METHOD="POST" name="FileForm" enctype="multipart/form-data"> 圖片: <input type="file" name="file1" size="20" id="file1"> <input type="button" value="確定上傳" onClick="checkFile()"> </form> </body> </html> <script language="JavaScript"> //by Bryan(不來ㄣ)//這裡控制要檢查的項目,true表示要檢查,false表示不檢查 var isCheckImageType = true;  //是否檢查圖片副檔名 var isCheckImageWidth = true;  //是否檢查圖片寬度 var isCheckImageHeight = true;  //是否檢查圖片高度 var isCheckImageSize = true;  //是否檢查圖片檔案大小 var ImageSizeLimit = 100000;  //上傳上限,單位:byte var ImageWidthLimit = 1200;  //圖片寬度上限 var ImageHeightLimit = 1000;  //圖片高度上限 function checkFile() { var f = document.FileForm; var re = /\.(jpg|gif)$/i;  //允許的圖片副檔名 if (isCheckImageType && !re.test(f.file1.value)) { alert("只允許上傳JPG或GIF影像檔"); } else { var img = new Image(); img.onload = checkImage; img.src = f.file1.value; } } function checkImage() { if (isCheckImageWidth && this.width > ImageWidthLimit) { showMessage('寬度','px',this.width,ImageWidthLimit); } else if (isCheckImageHeight && this.height > ImageHeightLimit) { showMessage('高度','px',this.height,ImageHeightLimit); } else if (isCheckImageSize && this.fileSize > ImageSizeLimit) { showMessage('檔案大小','kb',this.fileSize/1000,ImageSizeLimit/1000); } else { document.FileForm.submit(); } } function showMessage(kind,unit,real,limit) { var msg = "您所選擇的圖片kind為 real unit\n超過了上傳上限 limit unit\n不允許上傳!" alert(msg.replace(/kind/,kind).replace(/unit/g,unit).replace(/real/,real).replace(/limit/,limit)); } </script>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.