2012-01-04 75 views
3

我正在使用HTML表单上传图像文件。现在我正在使用服务器端验证来允许文件类型。但我想在客户端验证它。我在某些网站上看到,当我们选择文件时,其他文件类型会灰显。我认为这是一个很酷的选择。当我通过谷歌走,我发现这个将文件上传类型限制为仅限图像

<input id="my_file_element" type="file" name="file_0" accept="image/*"> 

但是这个我得到“所有文件”选项,以便达我就可以使其他的文件。我不需要那个。无论发生什么事,用户都应该被允许从他们的计算机中仅选择图像文件。你们有没有办法做到这一点?

这就是我的意思是灰色的。 enter image description here

+0

我在Firefox试过了,它在那里工作正常。你使用的是什么浏览器? – 2012-01-04 20:52:31

+0

您可以使用javascript来检查文件格式的扩展名。我会给你一些代码,但我吮吸在JavaScript。如果你喜欢,也许jQuery可以工作。 – Different55 2012-01-04 20:56:40

+0

@dotweb:我使用谷歌浏览器..在Firefox中可以使用“所有文件”选项并选择其他文件? – Deepak 2012-01-04 20:56:50

回答

3

accept属性是HTML5功能,因此很多浏览器都不支持此属性。

恐怕,只要我记得,获得更好的文件上传对话框(文件类型过滤器,多个文件...)的唯一方法就是使用Flash对象。

+0

你可以检查我的编辑?我已经上传了一张应该看起来如何的图片。我认为他们在这里没有使用闪存,因为接口来自MAC而不是闪存。我是谁? – Deepak 2012-01-04 21:13:48

0
Here is the HTML for image upload, By default it will show image files only in browsing window becauase we have put accept="image/*" . But still we can change it from the dropdown and it will show all files. So the Javascript part validates whether the selected file is an actual image or not. 

<div class="col-sm-8 img-upload-section"> 
    <input name="image3" type="file" accept="image/*" id="menu_images"/> 
    <img id="menu_image" class="preview_img" /> 
    <input type="submit" value="Submit" /> 
</div> 

Here on the change event first we are checking the size of the image. And in the second if condition we are checking whether it is an image file or not. 
this.files[0].type.indexOf("image") will be "-1" if it is not an image file. 

    document.getElementById("menu_images").onchange = function() { 
     var reader = new FileReader(); 
     if(this.files[0].size>528385){ 
      alert("Image Size should not be greater than 500Kb"); 
      $("#menu_image").attr("src","blank"); 
      $("#menu_image").hide(); 
      $('#menu_images').wrap('<form>').closest('form').get(0).reset(); 
      $('#menu_images').unwrap();  
      return false; 
     } 
     if(this.files[0].type.indexOf("image")==-1){ 
      alert("Invalid Type"); 
      $("#menu_image").attr("src","blank"); 
      $("#menu_image").hide(); 
      $('#menu_images').wrap('<form>').closest('form').get(0).reset(); 
      $('#menu_images').unwrap();   
      return false; 
     } 
     reader.onload = function (e) { 
      // get loaded data and render thumbnail. 
      document.getElementById("menu_image").src = e.target.result; 
      $("#menu_image").show(); 
     }; 

     // read the image file as a data URL. 
     reader.readAsDataURL(this.files[0]); 
    }; 
+0

虽然此代码可能有助于解决问题,但 提供了关于_why_和/或_how_的其他上下文,回答该问题将显着提高其长期价值。请[编辑]你的答案,添加一些 的解释。 – 2016-07-04 16:45:20