Search code examples
javascriptjqueryhtmljcropfileapi

Html 5 file api & jcrop issue


I render a picture in local using html5 and File API.

html:

<form action="/Picture/UpdateProfilePicture" id="profile_pic_form" method="post">
       <input type="file" id="file"><br>
</form>
<div>
       <output id="result"></output>
</div>

javascript:

<script type="text/javascript">
function handleFileSelect(evt) {
    var files = evt.target.files;
    var file = files[0];
    if (files[0].type.match('image.*')) {
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                // Render thumbnail.
                var span = document.createElement('span');
                span.innerHTML = ['<img id="cropbox" class="thumb" src="', e.target.result,
                    '" title="', escape(theFile.name), '"/>'].join('');
                document.getElementById('result').innerHTML = "";
                document.getElementById('result').insertBefore(span, null);
            };
        })(file);
        // Read in the image file as a data URL.
        reader.readAsDataURL(file);
        //$('#cropbox').Jcrop(options, function () { jcrop_api = this; });
    } else {
        alert("the file you entered is not a picture");
        $("#profile_pic_form").each(function() {
            this.reset();
        });
    }
}

$(document).ready(function() {
    // Check for the various File API support.
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        document.getElementById('file').addEventListener('change', handleFileSelect, false);
    } else {
        alert('The File APIs are not fully supported in this browser.');
    }
});

The js gets the file and generate the span & img tag inside the output tag.

What I want now is to "Jcrop" the picture BUT when I try $("#cropbox).Jcrop(); nothing happens, why ?


Solution

  • You are calling Jcrop in the wrong place. It's called before the image is created.

    if (files[0].type.match('image.*')) {
            var reader = new FileReader();
            reader.onload = (function (theFile) {
                return function (e) {
                    // Render thumbnail.
                    var span = document.createElement('span');
                    span.innerHTML = ['<img id="cropbox" class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/>'].join('');
                    document.getElementById('result').innerHTML = "";
                    document.getElementById('result').insertBefore(span, null);
                    $('#cropbox').Jcrop(); // <---- Should be here.
                };
            })(file);
    }