2011-11-02 28 views
11

tôi có các hình thức có các lĩnh vực follwing,Kiểm tra loại tệp khi gửi biểu mẫu?

<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> 

Tôi muốn xác nhận trước khi hình thức nộp. Ở đây làm thế nào tôi có thể xác nhận nếu người dùng chọn loại như hình ảnh và tải lên video hoặc chọn loại như video và tải lên hình ảnh?

Chúng tôi có thể đạt được điều này bằng javascript hoặc jquery.Bất kỳ cách nào để xác thực điều này?

Vui lòng giúp tôi về vấn đề này.

+1

tôi sử dụng jQuery Validation plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – Wayne

+1

có một "chấp nhận" thuộc tính đến sớm, nó không thực sự hỗ trợ nào, nhưng có một cái nhìn: http://www.w3schools.com/jsref/prop_fileupload_accept.asp Thông thường cách an toàn và hiệu quả nhất để làm điều này sẽ là serverside, nhưng bạn chỉ có thể kiểm tra các phần mở rộng tệp bằng javascript hoặc plugin xác thực của jQuery. – adeneo

Trả lời

39

Thay vì sử dụng onsubmit, sử dụng trình điều khiển của jQuery, và xác nhận sử dụng một số javascript như sau:

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 phiên bản ở đây, thử nghiệm trong IE8, RockMelt (dựa trên Chrome) và Firefox 7: http://jsfiddle.net/Ngrbj/4/

+0

Cảm ơn người dùng – mymotherland

+2

rất hữu ích có thể dễ dàng thay đổi phần mở rộng tệp thành "đánh lừa" xác thực như vậy, một giải pháp dựa trên mimetype sẽ tốt hơn (mặc dù, tôi không chắc liệu có tồn tại hay không, vẫn đang tìm kiếm) – loostro

+0

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

0

bạn có thể thử này:

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; 
} 

Bạn có thể sử dụng chức năng này trong thư mục checkcreateform()

0

Trước tiên, bạn nên thay đổi html của bạn như thế này:

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

Sau đó, bạn cần có một chức năng như thế này:

///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

Sử dụng tài sản các tập tin trên đầu vào: tập tin bạn có thể lặp thông qua đối tượng tập tin và kiểm tra loại tài sản

$('#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

Câu trả lời cung cấp tác phẩm, nhưng cái gì đó sẽ chạy nhanh hơn một chút với ít nhiều dòng cho mã xác nhận, sử dụng javascript chức năng mảng:

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; 
} 

Sau đó, câu lệnh if trong gửi mã chỉ là hoán đổi với:

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.'); 
    }   
Các vấn đề liên quan