0

I get a jpeg-image from this input field:

<input type="file" id="iAppIcon" accept="image/jpeg" form="imageAppIcon"></input>

How can i handle this now? When i use console.log($("#imageAppIcon").val()) i get "undefined".

I also cant find out the type of it.

What i want to do with it in the end, is to convert it into base64, to save it. I've seen quite a lot of posts about that using canvas but they used a different method to upload an image, at least it looked to me as if they would do that.

Gunder
  • 164
  • 2
  • 10

1 Answers1

0

Thanks to GregL

Check file type when form submit?

Instead of using onsubmit, use jQuery's submit handler, and validate using some javascript like the following:

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

});

Demo

Community
  • 1
  • 1
mymotherland
  • 7,968
  • 14
  • 65
  • 122