2017-02-11 55 views
0

我想检查其有效图像与否。 我的代码有效的图像如下,其工作完善,但是,当它的图像数组,然后它不起作用?我想在更改函数中使用数组名称

$("#file").change(function() { 
    var val = $(this).val(); 
    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){ 
     case 'gif': case 'jpg': case 'png': 
      //alert("an image"); 
      break; 
     default: 
      $(this).val(''); 
      // error message here 
      alert("Please Select Valid Image"); 
      break; 
    } 

}); 

工作完美的一个形象是指其对ID的工作,但现在我想和图像阵列来工作,那么我做什么?它可能与否?

<input id="file" type="file" name="images[]">Enter 8 Images For Batter Product View 
<input type="button" id="addmore" value="Add More Image"> 
中添加更多的图像

它给我的新形象,所以我需要一个数组,所以我想在数组中检查这种变化功能的有效图像或没有? 有可能吗?

感谢file类型的

+0

看看这里:http://stackoverflow.com/questions/17400191/get-the-files-chosen-using-the-input-type-file-multiple-and-store -them-in-a-a – Alex2php

回答

0

输入有称为files的属性是用户选择的文件的阵列。它包含名称和大小等信息。可以遍历和检查,如果用户输入了正确的图像或没有,像这样:

$("#file").change(function() { 
    var files = this.files; // get the array of files 
    var valid = true; 

    for(var i = 0; i < files.length && valid; i++) { // while there still files in the array, and valid still true 
     var val = files[i].name; // get the current filename 

     // check if the file is a valid image or not (if not don't forget to set valid to false) 
     switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){ 
      case 'gif': case 'jpg': case 'png': 
       // this is a valid image 
      break; 
      default: 
       // this is not a valid image so "valid" should become false 
       valid = false; 
      break; 
     } 
    } 

    if(!valid) // if valid was set to false insde the array (means an invalid file was selected) 
     alert("select valid images"); 
}); 

注:检查,如果文件是在客户端的图像并不总是有效的,用户可以通过将不是映像的文件的扩展名更改为例如.jpg来绕过检查。阅读更多here

+0

感谢replr先生。如何检查.jpg是否有效?先生 – Darshan

+0

@Darshan就像你拥有它的方式!只要你切换,而不是我的评论!但正如我所说,检查延伸并不总是有效! –

+0

@Darshan我在你的switch语句中添加了它! –

0

我只是简单地将id="file"更改为​​,它适用于我。

<input class="file" type="file" name="images[]">Enter 8 Images For Batter Product View 

<input type="button" id="addmore" value="Add More Image"> 

<script type="text/javascript"> 
$(".file").change(function() { 
    var val = $(this).val(); 
    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){ 
     case 'gif': case 'jpg': case 'png': 
      //alert("an image"); 
      break; 
     default: 
      $(this).val(''); 
      // error message here 
      alert("Please Select Valid Image"); 
      break; 
    } 

}); 

+0

其工作只有当它的第一个图像有效然后ts添加有效的所有标记 Darshan