2017-11-26 9 views
0

JavaScriptから画像のアップロードファイルの高さと幅を検証しようとしています。 falseを返しても動作しません。Javaスクリプトでの画像の幅と高さの確認 - Codeigniter

Javascriptのコード:

function Upload() { 
    var fileUpload = document.getElementById("userfile"); 
    var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$"); 
    if (regex.test(fileUpload.value.toLowerCase())) { 
     if (typeof(fileUpload.files) != "undefined") { 
      var reader = new FileReader(); 
      reader.readAsDataURL(fileUpload.files[0]); 
      reader.onload = function(e) { 
       var image = new Image(); 
       image.src = e.target.result; 
       image.onload = function() { 
        var height = this.height; 
        var width = this.width; 
        if (height < 227 || width < 300) { 
         alert("Height and Width should be above 227px by 300px."); 
         return false; 
        }else{ 
         alert("Uploaded image has valid Height and Width."); 
         return true; 
        } 
       }; 
      } 
     } else { 
      alert("This browser does not support HTML5."); 
      return false; 
     } 
    } else { 
     alert("Please select a valid Image file."); 
     return false; 
    } 
} 

HTML:

<form name="add_projects" id="add_projects" method="post" enctype="multipart/form-data"> 
    <div class="row"> 
     <div class="col-md-4"> 
      <div class="form-group"> 
       <label>Project Name</label> 
       <input type="text" name="project_name" id="project_name" class="form-control" value="<?php if(!empty($project)){ echo $project->project_name;}?>"> 
       <input type="hidden" name="id" id="id" value="<?php if(!empty($project)){ echo $project->id;}?>"> 
      </div> 
     </div> 
     <div class="col-md-4"> 
      <div class="form-group"> 
       <label>Project Sub Category Name</label> 
       <input type="text" name="project_sub_name" id="project_sub_name" class="form-control" value="<?php if(!empty($project)){ echo $project->project_sub_name;}?>"> 
      </div> 
     </div> 
     <div class="col-md-4"> 
      <div class="form-group"> 
       <label>Tags</label> 
       <input type="text" name="tags" id="tags" class="form-control" value="<?php if(!empty($project)){ echo $project->tags;}?>"> 
      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-md-12"> 
      <div class="form-group"> 
       <label>Poject Description</label> 
       <textarea id="editor1" name="project_description" class="form-control" rows="10" cols="80"><?php if(!empty($project)){ echo $project->project_description;}?></textarea> 
      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-md-6"> 
      <div class="form-group"> 
       <label>Current Image</label><br> 
       <?php if(!empty($project) && $project->image !=""){?> 
        <img height="227" width="450" src="<?=base_url()?>assets/images/projects/<?=$project->image?>"> 
       <?php }else{ echo "No Image Selected";} ?> 
      </div> 
     </div>      
     <div class="col-md-6"> 
      <div class="form-group"> 
       <label>New Image </label> 
       <div id="preview" style="width:100%"></div> 
      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-md-6"> 
      <div class="form-group"> 
       <label>Select Image </label> 
       <input type="file" name="userfile" id="userfile"> 
       <input type="hidden" name="old_file" value="<?php if(!empty($project)){ echo $project->image;}?>"> 
       <input type="hidden" name="id" value="<?php if(!empty($project)){ echo $project->id;}?>"> 
       <span class="error">(Image should be more then 300px in width and 227px in height or above)</span> 

      </div> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-md-3"> 
      <div class="form-group"> 
       <input type="submit" onclick="return Upload();" name="submit" id="submit" value="Save Changes" class="btn btn-primary"> 
      </div> 
     </div> 
    </div> 
</form> 

フォームが送信されますし、画像の高さと幅は、以下のピクセルを指定した場合でも、フォームの送信は停止されません。..

どこが間違っていますか?

フォーム(jquery.validate.min.js)に対してもJquery Validationを使用しています。

答えて

0

コードに間違いがあります。ファイル拡張子をチェックしようとしている方法が機能していません。ネストされた関数の内部から戻ろうとするとうまく動作しません。あなたは自由にjQueryを入手できますが、使用しないでください。明らかに、バニラのJavaScriptを可能な限り使用する方が良いですが、大きな混乱を招いています。私はいくつかの作業コードの小さな例をまとめ、可能な限り最小限に抑えようとしました。ファイルのサイズ、タイプ、および幅と高さが必要なためチェックします。

2つのバリデーションが行われていることがわかります。一度ファイル入力を変更し、フォームを一度送信します。これは、それができることをあなたに示すことです。この例は必ずしも完結しているわけではありませんが、あなたが行くべきです。私はそれをテストしました。それは起こっていることに従うのはかなり簡単です。

<!doctype html> 
<html lang="en-us"> 
    <head> 
     <meta charset="utf-8"> 
     <title>Get Image Size</title> 
    </head> 
    <body> 
     <form method="post" enctype="multipart/form-data" action="/whatever.php"> 
      <input id="file_input" type="file" name="userfile" /> 
      <input type="submit" name="submit" id="submit" value="Save Changes"> 
     </form> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     <script> 
      (function($){ 
       // Local namespace 
       var namespace = { 

        /* 
        * Check file for type and size on submission. 
        * It is assumed that the file is previously determined to exist. 
        * 
        * @param file element like $(<file_input>).files[0] 
        * @param int like 2000000 for 2MB 
        * @param string like "application/pdf|image/jpeg" 
        * @param int like 227 for min pixel height 227 
        * @param int like 300 for min pixel width 300 
        */ 
        validate_file_upload: function(file, max_file_size, allowed_types, min_img_height, min_img_width){ 
         if(! 'size' in file || ! 'type' in file) 
          return false; 
         if(file.size > max_file_size) 
          return false; 
         if(file.type != '' && allowed_types.indexOf(file.type) == -1) 
          return false; 
         var url = URL.createObjectURL(file); 
         var img = new Image; 
         var error = false; 
         img.onload = function(){ 
          if(img.height < min_img_height || img.width < min_img_width){ 
           error = true; 
          } 
         }; 
         img.src = url; 
         if(error) 
          return false; 
         return true; 
        }, 

        /* 
        * Instant validation of file input on field change. 
        * 
        * @param file element like $(<file_input>).files[0] 
        * @param int like 2000000 for 2MB 
        * @param string like "application/pdf|image/jpeg" 
        * @param int like 40000000 for 40MB 
        * @param int like 227 for min pixel height 227 
        * @param int like 300 for min pixel width 300 
        */ 
        validate_file_input_on_change: function(file, max_bytes, allowed_mimes, post_max_size, min_img_height, min_img_width){ 
         var error = false; 
         /* Is the file even a file? */ 
         if(! 'size' in file || ! 'type' in file) 
         { 
          error = true; 
          alert('File not able to be validated.'); 
         } 
         /* Is filesize too large? */ 
         else if(file.size > max_bytes){ 
          error = true; 
          var readableSize = this._humanFileSize(file.size, true); 
          alert('File size of ~' + readableSize + ' too large to upload.'); 
         } 
         /* Else filesize is not too large */ 
         else{ 
          /* Is mime type allowed? */ 
          if(file.type != '' && allowed_mimes.indexOf(file.type) == -1){ 
           error = true; 
           alert('Mime type ' + file.type + ' not uploadable.'); 
          } 
          /* Else mime type was allowed */ 
          else{ 
           var fields_total = 0; 
           $('input[type="file"]').each(function(i,el){ 
            if(el.files[0] != undefined) 
             fields_total += el.files[0].size; 
           }); 
           /* Is total combined filesize meet server expectations */ 
           if(fields_total > post_max_size){ 
            error = true; 
            var combinedTotal = this._humanFileSize(fields_total, true); 
            var postMax = this._humanFileSize(post_max_size, true); 
            alert('Combined filesize total of ' + combinedTotal + ' exceeds the server limitation of ' + postMax + '.\n\nPlease reduce the number of uploads.'); 
           } 
          } 
         } 
         /* Only check image dimensions if there is no existing error */ 
         if(! error){ 
          var url = URL.createObjectURL(file); 
          var img = new Image; 
          img.onload = function(){ 
           if(img.height < min_img_height || img.width < min_img_width){ 
            error = true; 
            alert('Image height and/or width not large enough.'); 
           } 
          }; 
          img.src = url; 
         } 
         return ! error; 
        }, 

        /* 
        * Convert filesize in bytes to human readable MBs. 
        * Used by funcs.validate_file_input_on_change(). 
        * 
        * @param int filesize in bytes, provided by File API 
        * @param bool is size vs size on disk 
        */ 
        _humanFileSize: function(bytes, si) { 
         var thresh = si ? 1000 : 1024; 
         if(Math.abs(bytes) < thresh) 
          return bytes + ' B'; 
         var units = si 
          ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] 
          : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']; 
         var u = -1; 
         do { 
          bytes /= thresh; 
          ++u; 
         } while(Math.abs(bytes) >= thresh && u < units.length - 1); 
         return bytes.toFixed(1) + units[u]; 
        } 

       // End local namespace 
       }; 

       window.funcs = (window.funcs) 
        ? $.extend(window.funcs, namespace) 
        : namespace; 

      })(this.jQuery); 

      $(document).ready(function(){ 

       $('#file_input').on('change', function(){ 
        var file = this.files[0]; 
        // Check filesize and file type 
        var status = funcs.validate_file_input_on_change( 
         file, 
         // Max bytes 
         200000, 
         // Allowed mimes 
         'image/jpeg|image/png|image/gif', 
         // Max post bytes 
         40000000, 
         // Min height 
         227, 
         // Min width 
         300 
        ); 
       }); 

       $('#submit').on('click', function(e){ 
        var file = $('#file_input')[0].files[0]; 
        if(funcs.validate_file_upload(
         file, 
         // Max bytes 
         200000, 
         // Allowed mimes 
         'image/jpeg|image/png|image/gif', 
         // Min height 
         227, 
         // Min width 
         300 
        )){ 
         return true; 
        } 
        e.preventDefault(); 
        return false; 
       }); 

      }); 
     </script> 
    </body> 
</html> 
+0

ブライアンに感謝します。ありがとうございました。 –

関連する問題