0

Basically I have a input type="file" that the users should only select images, and if the file chosen is image the I need my form to submit otherwise pop up an error. so far I could do this:

$(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        checkforImage($('#Propicselecter_file'), "yes");
    });
    $('[type="file"]').change(function() {
        var fileInput = $(this);
        checkforImage(fileInput, "no");
    });
});

function submitmyform(fileInput){
    $.ajax({
        url: '../propicuploader',
        type: 'POST',
        processData: false,
        data: fileInput[0];
        success: function(data){
        }
    });
}

function checkforImage(fileInput, submitornot){
    if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
        var url = window.URL || window.webkitURL;
        var image = new Image();
        image.onload = function() {
            $("#NotPictureerror_spn").text("");
            if(submitornot == "yes"){
                submitmyform(fileInput);
            }
        };
        image.onerror = function() {
            $("#NotPictureerror_spn").text("Chosen file is not an image, Please Try Again");
        };
        image.src = url.createObjectURL(fileInput[0].files[0]);
    }
}

I don't know why but here if the file is image or not the form gets to submit. so can you tell me how to check if the file is an image, otherwise pop an error.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
darees
  • 17
  • 2
  • 8
  • 1
    This could solve your question http://stackoverflow.com/questions/651700/how-to-have-jquery-restrict-file-types-on-upload Checking for the extension of the file – DaniP Sep 09 '16 at 21:25

1 Answers1

0

When taking the input file name, save it as a string, Then use the string split function to find out the file type e.g.

string input = "image.jpg";
string[] check = input.split(".");
if (check[1] == "jpg")
{
//code that selects image
}

Then create a bool that checks if the image is of the type you want, or insert the code into the IF statement.

Hope this helps

Jack Miller
  • 325
  • 1
  • 16