2013-02-13 17 views
12

Sto usando uploadify per caricare file con Codeigniter. E prima di caricare il file, devo solo controllare se l'estensione del file è corretta o meno. Ho provato con http://jquery.bassistance.de/ e anche con http://forum.jquery.com/jquery - Controllare l'estensione del file prima di caricare

Bur non ha ottenuto risultati corretti. Qualcuno può dirmi come posso fare lo stesso?

Grazie in anticipo ...

+1

Hai controllato http://jquery.bassistance.de/validate/demo/file_input.html –

+0

No, è veramente bello. Puoi dirmi dov'è il codice sorgente disponibile insieme alla demo? – V15HM4Y

+0

http://jquery.bassistance.de/validate/jquery-validation-1.11.0.zip –

risposta

13

Vorrei ringraziare la persona che ha pubblicato la risposta, ma ha cancellato il post. Possiamo farlo in questo modo.

$("#yourElem").uploadify({ 
    'uploader': ..., 
    'script': ... 
    'fileExt' : '*.jpg;*.gif;', //add allowed extensions 
    ....., 
    'onSelect': function(e, q, f) { 
     var validExtensions = ['jpg','gif']; //array of valid extensions 
     var fileName = f.name; 
     var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1); 
     if ($.inArray(fileNameExt, validExtensions) == -1){ 
      alert("Invalid file type"); 
      $("#yourElem").uploadifyCancel(q); 
      return false; 
     } 
    } 
}); 

Grazie per la risposta, in realtà funzionato ...

+0

Semplice e utile. Grazie. – QMaster

+0

ottenere errore f non è definito – OBAID

34

Se si vuole fare senza un plugin è possibile utilizzare il seguente.

JavaScript, utilizzando jQuery:

$(document).ready(function(){ 
    $("#your_form").submit(function(submitEvent) { 

     // get the file name, possibly with path (depends on browser) 
     var filename = $("#file_input").val(); 

     // Use a regular expression to trim everything before final dot 
     var extension = filename.replace(/^.*\./, ''); 

     // Iff there is no dot anywhere in filename, we would have extension == filename, 
     // so we account for this possibility now 
     if (extension == filename) { 
      extension = ''; 
     } else { 
      // if there is an extension, we convert to lower case 
      // (N.B. this conversion will not effect the value of the extension 
      // on the file upload.) 
      extension = extension.toLowerCase(); 
     } 

     switch (extension) { 
      case 'jpg': 
      case 'jpeg': 
      case 'png': 
       alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)"); 

      // uncomment the next line to allow the form to submitted in this case: 
//   break; 

      default: 
       // Cancel the form submission 
       submitEvent.preventDefault(); 
     } 

    }); 
}); 

HTML:

<form id="your_form" method="post" enctype="multipart/form-data"> 
    <input id="file_input" type="file" /> 
    <input type="submit"> 
</form> 
22

È possibile ottenere questo utilizzando jQuery

HTML

<input type="file" id="FilUploader" /> 

JQuery

$("#FilUploader").change(function() { 
     var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp']; 
     if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) { 
      alert("Only formats are allowed : "+fileExtension.join(', ')); 
     } 
    }); 

Per maggiori informazioni Click Here

+3

Invece di 'split()' sarebbe bello usare 'lastIndexOf ('.')' Per assicurarsi che si stia usando l'ultimo punto, che si riferisce all'estensione. –

0
 function yourfunctionName() { 
      var yourFileName = $("#yourinputfieldis").val(); 

      var yourFileExtension = yourFileName .replace(/^.*\./, ''); 
      switch (yourFileExtension) { 
       case 'pdf': 
       case 'jpg': 
       case 'doc': 
        $("#formId").submit();// your condition what you want to do 
        break; 
       default: 
        alert('your File extension is wrong.'); 
        this.value = ''; 
      } 
//    $("#upload_" + id).submit(); 
     } 
3

Ecco un semplice codice javascript per la validazione, e dopo che lo convalida pulirà il file di input.

<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

Se non si desidera utilizzare $(this).val(), si può provare:

var file_onchange = function() { 
    var input = this; // avoid using 'this' directly 

    if (input.files && input.files[0]) { 
    var type = input.files[0].type; // image/jpg, image/png, image/jpeg... 

    // allow jpg, png, jpeg, bmp, gif, ico 
    var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/; 

    if (type_reg.test(type)) { 
     // file is ready to upload 
    } else { 
     alert('This file type is unsupported.'); 
    } 
    } 
}; 

$('#file').on('change', file_onchange); 

Spero che questo aiuti!

0

Il seguente codice consente di caricare file gif, png, jpg, jpeg e bmp.

var extension = $('#your_file_id').val().split('.').pop().toLowerCase(); 

if($.inArray(extension, ['gif','png','jpg','jpeg','bmp']) == -1) { 
    alert('Sorry, invalid extension.'); 
    return false; 
} 
Problemi correlati