0

I haven't used HTML5 File API much, so am pretty new to it.

I am trying to get the width and height of a file from the file upload field '#submission-file' field into two variables.

Here is the code I have:

    var fileWidth = 0;
    var fileHeight = 0;
    var url = window.URL || window.webkitURL;
    var fileField = $('#submission-file')[0].files[0];
    var image = new Image();
    image.onload = function() {
        fileWidth = $('#submission-file').width;
        fileHeight = $('#submission-file').height;
    };
    image.src = url.createObjectURL(fileField); 

Can anyone show me what I am doing wrong?

2
  • 1
    This might help: stackoverflow.com/questions/5173796/html5-get-image-dimension Commented Jun 13, 2013 at 13:13
  • @tymeJV That Q&A doesn't explain why he's unable to get the width and height of the file in his onload callback. When the onload callback is called above, the file should be loaded - thus, he should be able to access those properties. Commented Jun 13, 2013 at 13:21

1 Answer 1

4

You could use this snippet, give you the idea:

http://jsfiddle.net/Mqvgx/

function getImgSize(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#testImg').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$('#testImg').on('load', function () {
    alert($(this).width() + '*' + $(this).height());
})

$("input").change(function () {
    getImgSize(this);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.