Cómo hacer que jQuery restrinja los tipos de archivos al subir?


Me gustaría que jQuery limitara un campo de carga de archivos a solo jpg/jpeg, png y gif. Ya estoy haciendo la comprobación de backend con PHP. Ya estoy ejecutando mi botón enviar a través de una función JavaScript, así que realmente solo necesito saber cómo verificar los tipos de archivos antes de enviar o alertar.

Author: TooTone, 2009-03-16

13 answers

Puede obtener el valor de un campo de archivo igual que cualquier otro campo. Sin embargo, no puedes alterarlo.

Así que para superficialmente comprobar si un archivo tiene la extensión correcta, podrías hacer algo como esto:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}
 262
Author: Paolo Bergantino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 17:31:34

No es necesario ningún plugin para esta tarea. Improvisado esto junto a un par de otros guiones:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

El truco aquí es establecer el botón de carga en desactivado a menos y hasta que se seleccione un tipo de archivo válido.

 37
Author: Christian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 00:11:48

Puedes usar el plugin de validación para jQuery: http://docs.jquery.com/Plugins/Validation

Sucede que tiene una regla accept() que hace exactamente lo que necesita: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension

Tenga en cuenta que el control de la extensión del archivo no es a prueba de balas, ya que no está relacionado de ninguna manera con el tipo mime del archivo. Así que podrías tener una .png que es un documento de Word y una .doc es una imagen PNG perfectamente válida. Así que no olvídate de hacer más controles del lado del servidor;)

 26
Author: Julian Aubourg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-21 14:02:16

¿No quieres comprobar más bien en MIME que en cualquier extensión que el usuario está mintiendo? Si es así, entonces es menos de una línea:

<input type="file" id="userfile" accept="image/*|video/*" required />
 19
Author: Leo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-28 14:41:00

Para el front-end es bastante conveniente poner el atributo 'accept' si está utilizando un campo de archivo.

Ejemplo:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

Un par de notas importantes:

 19
Author: dhruvpatel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:35

Para mi caso utilicé los siguientes códigos:

    if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {              
    alert('You must select an image file only');               
    }
 4
Author: vanessen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-16 11:26:54

Intento escribir un ejemplo de código de trabajo, lo pruebo y todo funciona.

Hare es el código:

HTML:

<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />

Javascript:

 //function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
    var val = $(element).val(); //get file value

    var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention 
    if ($.inArray(ext, extentionsArray) == -1) {
        alert('false extension!');
    }

    var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
    if (fileSize > maxSize) {
        alert("Large file");// if Maxsize from Model > real file size alert this
    }
}
 2
Author: Avtandil Kavrelishvili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 09:38:10

Este código funciona bien, pero el único problema es que si el formato del archivo es diferente de las opciones especificadas, muestra un mensaje de alerta pero muestra el nombre del archivo mientras que debería descuidarlo.

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});
 1
Author: Abhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 22:52:33

Este ejemplo solo permite cargar imágenes PNG.

HTML

<input type="file" class="form-control" id="FileUpload1" accept="image/png" />

JS

$('#FileUpload1').change(
                function () {
                    var fileExtension = ['png'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.png' format is allowed.");
                        this.value = ''; // Clean field
                        return false;
                    }
                });
 1
Author: Academy of Programmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 23:01:35
<form enctype="multipart/form-data">
   <input name="file" type="file" />
   <input type="submit" value="Upload" />
</form>
<script>
$('input[type=file]').change(function(){
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    //your validation
});
</script>
 0
Author: Khaihkd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-28 02:40:02

Si estás tratando con múltiples cargas de archivos (html 5), tomé el comentario sugerido y lo modificé un poco:

    var files = $('#file1')[0].files;
    var len = $('#file1').get(0).files.length;

    for (var i = 0; i < len; i++) {

        f = files[i];

        var ext = f.name.split('.').pop().toLowerCase();
        if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            alert('invalid extension!');

        }
    }
 0
Author: Jason Roner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-09 21:18:26
function validateFileExtensions(){
        var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
        var fileErrors = new Array();

        $( "input:file").each(function(){
            var file = $(this).value;
            var ext = file.split('.').pop();
            if( $.inArray( ext, validFileExtensions ) == -1) {
                fileErrors.push(file);
            }
        });

        if( fileErrors.length > 0 ){
            var errorContainer = $("#validation-errors");
            for(var i=0; i < fileErrors.length; i++){
                errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
            }
            return false;
        }
        return true;
    }
 -1
Author: M Saqib Sarwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-26 12:07:13

Aquí hay un código simple para la validación de javascript, y después de validarlo limpiará el archivo de entrada.

<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>

function validate(file) {
    var ext = file.split(".");
    ext = ext[ext.length-1].toLowerCase();      
    var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];

    if (arrayExtensions.lastIndexOf(ext) == -1) {
        alert("Wrong extension type.");
        $("#image").val("");
    }
}
 -1
Author: matheushf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 13:23:52