upload image

by Timoleon Pagounas

HTML

<div id="file">Choose file</div>
<form>
    <input type="file" name="file" />
    <img id="blah" src="#" alt="your image" />
</form>

CSS

#blah { display:none }
#file {
    display:none;
    color: #888;
	border: 1px solid #ccc;
	font-family: Cantarell, Verdana, sans-serif;
	font-weight: bold;
	font-size: 15px;
	width: 300px;
    height: 35px;
    line-height: 35px;
	padding: 0 25px;
	margin: 20px 0;
	float: left;
	border-radius: 6px;
	-moz-border-radius: 6px;
	-webkit-border-radius: 6px;
	background-image:url(http://admin.rafflebananza.com/img/input_middle.png);
	background-size:100% 100%;
}

JavaScript

var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);

fileInput.change(function(){
    readURL(this);
})

$('#file').click(function(){
    fileInput.click();
}).show();

function readURL(input) {
    $('#blah').hide();
    if (input.files && input.files[0]) {
        var goUpload = true;
        var uploadFile = input.files[0];
        if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
            $('#file').effect( "shake" );
            $('#file').text('You must select an image file only');
            setTimeout(function() { $('#file').text('Choose file');},5000);
            goUpload = false;
        }
        if (uploadFile.size > 2000000) { // 2mb
            //common.notifyError('Please upload a smaller image, max size is 2 MB');
            $('#file').text('Please upload a smaller image, max size is 2 MB');
            setTimeout(function() { $('#file').text('Choose file');},5000);
            goUpload = false;
        }
        if (goUpload) {
            $('#file').text("Uploading "+uploadFile.name);
            var reader = new FileReader();
            reader.onload = function (e) {
                maxWidth = 100; // Max width for the image
                maxHeight = 100; // Max height for the image
                ratio = 0; // Used for aspect ratio
                width = this.width(); // Current image width
                height = this.height(); // Current image height
                
                // Check if the current width is larger than the max
                if (width > maxWidth) {
                    ratio = maxWidth / width; // get ratio for scaling image
                    $('img#blah').css("width", maxWidth + 'px'); // Set new width
                    $('img#blah').css("height", height * ratio + 'px'); // Scale height based on ratio
                    height = height * ratio; // Reset height to match scaled image
                }
                
           ...