Ограничить тип загрузки файла только изображения - PullRequest
3 голосов
/ 05 января 2012

Я использую форму HTML для загрузки файлов изображений.Теперь я использую проверку на стороне сервера, чтобы разрешить типы файлов.Но я хочу проверить это и на стороне клиента.Я видел на некоторых сайтах, которые выделяют другие типы файлов, когда мы выбираем файл.Я думаю, что это крутой вариант.Когда я шел через Google, я обнаружил, что

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

Но с этим я получаю опцию «Все файлы», так что я могу включить и другие файлы.Мне это не нужно.Независимо от того, что происходит, пользователь должен иметь возможность выбирать только файлы изображений со своего компьютера.Ребята, вы знаете, как это сделать?

Это то, что я имел в виду, говоря, что уклоняюсь.enter image description here

Ответы [ 2 ]

3 голосов
/ 05 января 2012

Этот атрибут accept является функцией HTML5 и поэтому не поддерживается многими браузерами.

Боюсь, что, насколько я помню, единственный другой способ улучшить диалог загрузки файлов (фильтры типов файлов, несколько файлов ...) - это использовать объект Flash.

0 голосов
/ 28 июня 2016
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]);
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...