How can I getting the image type in ajax to allow PNG and JPG only before sending data?
$(document).ready(function() {
$("#sharepostbtnX2").click(function(){
//--HERE CAN ADD AJAX CODE TO ALLOW PNG AND JPG IMAGES ONLY--
var formData = new FormData($("#postform")[0]);
$.ajax({
url: "postingthepost.php",
type: 'POST',
data: formData,
async: false,
success: function (response) {
$(response).hide().prependTo("#responds").fadeIn();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<input type="file" accept="image/*" id="snap" name="snap" multiple="no" title="Choose a Image file to upload" />
in you javascript
var input = $('#snap')[0];
if (input.files && input.files[0]) {
var oFile = input.files[0];
var oFile = oFile.size;
var oFileType = oFile.type
//Option 1
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (! rFilter.test(oFileType)) {
alert('Please select a valid image file (jpg and png are allowed)');
return;
}
//Option 2
if (!oFile.fileName.match(/\.(jpg|jpeg|png|gif)$/)){
//TODO do your validation for image type then process ajax
}
}
try this,
var formData = new FormData($("#postform")[0]);
var ext = formData.val().split('.').pop().toLowerCase();
if($.inArray(ext, ['png','jpg','jpeg']) == -1) {
alert('InValid Image');
}else{
alert('Valid Image');
//do your AJAX Function..
}