多個上傳檔案用js驗證檔案的格式和大小的方法(推薦),上傳檔案js

來源:互聯網
上載者:User

多個上傳檔案用js驗證檔案的格式和大小的方法(推薦),上傳檔案js

html部分:

 <dsp:form action="${originatingRequest.requestURI}" method="post" enctype="multipart/form-data">  <dsp:input type="file" bean="ReturngoodsFormHandler.uploadedFile1" id="uploadedFile1" value="" onchange="checkfile('uploadedFile1');"/>  <dsp:input type="file" bean="ReturngoodsFormHandler.uploadedFile2" id="uploadedFile2" value="" onchange="checkfile('uploadedFile2');"/>  <a class="btn_sprite btn_font14_red" href="javascript:;" rel="external nofollow" ><span>提交申請</span></a>   <dsp:input type="submit" style="display:none;" bean="ReturngoodsFormHandler.submitReturngoods" id="submitReturngoods" value="Add"/>   </dsp:form>

需要注意:上傳檔案要有一個id,然後onchage事件裡加一個id的名稱;

js部分:

//將驗證的設定和錯誤資訊抽離出來,有利於最後submit時候做判斷var flag=true; var errorinfo="";//驗證檔案的格式 function checkfile(filenames){  filename=document.getElementByIdx_x_x(filenames).value;  var re=/(.[.]bmp)$|(.[.]gif)$|(.[.]jpg)$|(.[.]png)$|(.[.]jpeg)$/i;  if (!re.test(filename)) {  errorinfo = "只支援bmp,gif,jpg,png,jpeg格式檔案,請重新上傳";  alert(errorinfo);  flag = false;  return false;   }//驗證檔案的大小   if(document.getElementByIdx_x_x(filenames).size>8000){   errorinfo = "檔案必須小於800KB,圖片太大 size:"+document.getElementByIdx_x_x_x_x_x(filenames).size;   alert(errorinfo);   return false;   } } jQuery('.btn_font14_red').click(function(){ if(flag==true){  $("#submitReturngoods").click(); }else{  alert(errorinfo);  return false; }  });

注意:這麼做的好處是:第一:上傳檔案的時候,如果有錯誤,第一時間通知使用者,使用者去修改;

第二:如果使用者最後填完了,雖然之前有提示句,但是使用者忘了是什麼,點擊提交的時候,仍然可以提示使用者問題的原因。同時將錯誤資訊和設定值放在最外面,而不用再次驗證,可以節省頁面效率。

(document.getElementByIdx_x_x(filenames) 不知道為啥發表的時候,總是多個_x,去又去不掉,大家在copy的時候記得去掉哈)

以上這篇多個上傳檔案用js驗證檔案的格式和大小的方法(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.