如何在ajax中获取图像类型以仅在发送数据之前允许PNG和JPG?
$(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;
});
答案 0 :(得分:1)
<input type="file" accept="image/*" id="snap" name="snap" multiple="no" title="Choose a Image file to upload" />
在你的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
}
}
答案 1 :(得分:0)
试试这个,
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..
}