Method for verifying file format and size with js for multiple uploaded files of recommendation

  • 2021-08-03 08:20:39
  • OfStack

html section:


 <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> Submit an application </span></a>

   <dsp:input type="submit" style="display:none;" bean="ReturngoodsFormHandler.submitReturngoods" id="submitReturngoods" value="Add"/>

   </dsp:form>

It should be noted that the uploaded file should have an id, and then the name of an id should be added to the onchage event;

js section:


// Pull out the validated settings and error messages, which is beneficial to the final submit Time to make judgments 

var flag=true;
 var errorinfo="";

// Verify the format of the file 
 function checkfile(filenames){
  filename=document.getElementByIdx_x_x(filenames).value;

  var re=/(.[.]bmp)$|(.[.]gif)$|(.[.]jpg)$|(.[.]png)$|(.[.]jpeg)$/i;
  if (!re.test(filename)) {
  errorinfo = " Support only bmp,gif,jpg,png,jpeg Format file, please upload it again ";
  alert(errorinfo);
  flag = false;
  return false;
   }

// Verify the size of the file 
   if(document.getElementByIdx_x_x(filenames).size>8000){
   errorinfo = " File must be less than 800KB, Picture too large  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;
 } 

 });

Note: The advantages of doing this are: 1: When uploading files, if there are errors, inform the user in the first time, and the user will modify them;

2: If the user finishes, although there is a prompt statement before, but the user forgets what it is, when clicking Submit, the user can still be prompted for the cause of the problem. Putting error messages and setting values outermost at the same time without re-validating can save page efficiency.

(document.getElementByIdx_x_x) I don't know why when it is published, there are always multiple _ x, which can't be removed. Remember to remove it when you are copy.)


Related articles: