将文件上载类型限制为仅限Image

时间:2012-01-04 20:50:46

标签: html file-upload

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

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

但有了这个,我得到“所有文件”选项,所以我也可以启用其他文件。我不需要那个。无论发生什么,都应该允许用户从他们的计算机中仅选择图像文件。你们知道这样做的方法吗?

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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]);
    };
相关问题