JSFiddle - React, Tailwind, and code Playground
HTML
<div id="file">Choose file</div>
<input type="file" name="file" />
<div class="Img">
<img id="blah" src="#" alt="your image" />
</div>
CSS
.Img {
height:120px;
width:120px;
overflow:hidden;
}
#blah {
float:left;
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) {
$('#blah').attr('src', e.target.result);
width = $('#blah').width(); // Current image width
height = $('#blah').height(); // Current image height
if ( width > 119 && height > 119 ){
if (width > height) {
ratio = width / height; // get ratio for scaling image
newWidth = 120 * ratio;
margin = '-' + (newWidth - 120) /2 + 'px';
$('img#blah').css("width", newWidth + 'px'); // Set new width
$('img#blah').css("height", '120px'); // Scale height based on ratio
$('#blah').css("margin-left", margin);
}
if (height > width) {
...