2011-11-02 17 views
11

Mam formularz mający pola follwing,Sprawdź typ pliku po przesłaniu formularza?

<form onsubmit="return checkcreateform()" action="/gallery/create" method="post" enctype="multipart/form-data"> 
    <label>Type:*</label> 
    <label for="type-1"> 
    <input type="radio" checked="checked" value="1" id="type-1" name="type">Image 
    </label> 
    <br> 
    <label for="type-2"> 
    <input type="radio" value="2" id="type-2" name="type">Video 
    </label> 
    <label class="itemdetailfloatL required" for="file">File:*</label> 
    <input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE"> 
    <input type="file" tabindex="5" class="text-size text" id="file" name="file"> 
<input type="submit" value="Create" id="submit" name="submit"> 
</form> 

Chcę potwierdzić przed wysłaniem formularza. Jak mogę sprawdzić, czy użytkownik wybrał typ jako Obraz i załadował wideo, czy też wybierz typ wideo i przesłać obraz?

Możemy to osiągnąć za pomocą javascript lub jquery.Każdy szybki sposób na sprawdzenie tego?

Uprzejmie mi pomóż w tej sprawie.

+1

używam plugin jQuery Walidacja: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – Wayne

+1

istnieje „akceptować” atrybut wkrótce, to naprawdę nie jest jeszcze obsługiwany, ale spójrz na: http://www.w3schools.com/jsref/prop_fileupload_accept.asp Normalnie Jedynym bezpiecznym i skutecznym sposobem na zrobienie tego będzie serveride, ale możesz po prostu sprawdzić rozszerzenia plików za pomocą wtyczki javascript lub jQuery's validate. – adeneo

Odpowiedz

39

Zamiast onsubmit, należy złożyć obsługi jQuery i zatwierdź za pomocą jakiś skrypt tak: wersja

function getExtension(filename) { 
    var parts = filename.split('.'); 
    return parts[parts.length - 1]; 
} 

function isImage(filename) { 
    var ext = getExtension(filename); 
    switch (ext.toLowerCase()) { 
    case 'jpg': 
    case 'gif': 
    case 'bmp': 
    case 'png': 
     //etc 
     return true; 
    } 
    return false; 
} 

function isVideo(filename) { 
    var ext = getExtension(filename); 
    switch (ext.toLowerCase()) { 
    case 'm4v': 
    case 'avi': 
    case 'mpg': 
    case 'mp4': 
     // etc 
     return true; 
    } 
    return false; 
} 

$(function() { 
    $('form').submit(function() { 
     function failValidation(msg) { 
      alert(msg); // just an alert for now but you can spice this up later 
      return false; 
     } 

     var file = $('#file'); 
     var imageChosen = $('#type-1').is(':checked'); 
     if (imageChosen && !isImage(file.val())) { 
      return failValidation('Please select a valid image'); 
     } 
     else if (!imageChosen && !isVideo(file.val())) { 
      return failValidation('Please select a valid video file.'); 
     } 

     // success at this point 
     // indicate success with alert for now 
     alert('Valid file! Here is where you would return true to allow the form to submit normally.'); 
     return false; // prevent form submitting anyway - remove this in your environment 
    }); 

}); 

jsFiddle tu badanej w IE8, RockMelt (bazuje na Chrome) i Firefox 7: http://jsfiddle.net/Ngrbj/4/

+0

Dzięki bardzo pomocnemu użytkownikowi – mymotherland

+2

użytkownik może z łatwością zmienić rozszerzenie pliku na "fool" takie sprawdzanie poprawności, rozwiązanie oparte na typie MIME byłoby lepsze (choć nie jestem pewien, czy takie istnieje, wciąż szukając go samemu) – loostro

+0

zobacz http://stackoverflow.com/questions/7395548/js-and-type-match-as-file-mime-type-need-advice – loostro

0

można spróbować to:

function getFile(fieldId) { 
    var fileInsert = document.getElementById(fieldId).value; 
     fileName = fileName.split('/'); 
     fileName = fileName[fileName.length]; 
     extentions = fileName.split('.'); 
     extentions = extentions[extentions.length]; 
    return extentions; 
} 

Można użyć tej funkcji w checkcreateform()

0

najpierw trzeba zmienić html tak:

<input type="file" tabindex="5" class="text-size text" id="file" name="file" onchange="checkeExtension(this.value,"submit");"> 

Następnie trzeba funkcję tak:

///image 1 and video 2 
//you can extend file types 
var types= { 
    'jpg' :"1", 
    'avi' :"2", 
    'png' :"1", 
    "mov" : "2", 
} 

function checkeExtension(filename,submitId) { 
    var re = /\..+$/; 
    var ext = filename.match(re); 
    var type = $("input[type='radio']:checked").val(); 
    var submitEl = document.getElementById(submitId); 

    if (types[ext] == type) { 
     submitEl.disabled = false; 
     return true; 
    } else { 
     alert("Invalid file type, please select another file"); 
     submitEl.disabled = true; 
     return false; 
    } 
} 
2

Korzystanie własność pliki na wejściu: plik można pętli obiektów plików i sprawdzić właściwość typu

$('#upload').on("change", function(){ 
 
    
 
     var sel_files = document.getElementById('upload').files; 
 
     var len = sel_files.length; 
 
    
 
     for (var i = 0; i < len; i++) { 
 

 
      var file = sel_files[i]; 
 
      
 
      if (!(file.type==='application/pdf')) { 
 
      continue; 
 
      } 
 
      } 
 

 
     });
<div class="modal"> 
 
    <form id="form-upload"> 
 
    <input type="file" name="upload" id="upload" multiple> 
 
    <br/> 
 
     
 
</form> 
 
</div>

3

Odpowiedź przewidziane prace, ale coś, co będzie działać nieco szybciej, o wiele mniejszej liczby linii kodu walidacji przy użyciu javascript funkcje tablicy:

var extensionLists = {}; //Create an object for all extension lists 
extensionLists.video = ['m4v', 'avi','mpg','mp4', 'webm']; 
extensionLists.image = ['jpg', 'gif', 'bmp', 'png']; 

// One validation function for all file types  
function isValidFileType(fName, fType) { 
    return extensionLists[fType].indexOf(fName.split('.').pop()) > -1; 
} 

Następnie if w przedkładać kod jest po prostu zamienione z:

if (imageChosen && !isValidFileType(file.val(), 'image')) { 
     return failValidation('Please select a valid image'); 
    } 
else if (!imageChosen && !isValidFileType(file.val(), 'video')) { 
     return failValidation('Please select a valid video file.'); 
    }   
Powiązane problemy