Raymart Calinao Raymart Calinao - 1 month ago 11
PHP Question

Div that acts as file upload?

I simply want to make an upload or something like browse file on the div itself like act as a file input and trigger its function but my problem was i'm new to java script and quite embarrassed myself for brainstorming for almost an hour and looking for the same problem on the internet. so i don't have any other choice but to ask question here




my code


<form id="test_form" method="GET" action="">
<div id="pic1" style="border:1px solid white;width:200px;height:150px;float:left;margin:10px;" onclick="Upload">
<input type="file" name="fileToUpload" id="fileToUpload" size="1" style="display:none;">


</div></form>



while my file input is hidden inside the div


<script type="">

$('#pic1').click(function (Upload) {
$('#fileToUpload').click();
});

</script>

Answer

$(document).ready(function() {

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

            reader.onload = function (e) {
                $('.profile-pic').attr('src', e.target.result);
            }
    
            reader.readAsDataURL(input.files[0]);
        }
    }
    

    $(".file-upload").on('change', function(){
        readURL(this);
    });
    
    $(".upload-button").on('click', function() {
       $(".file-upload").click();
    });
});
.upload-button {
    padding: 4px;
    border: 1px solid black;
    border-radius: 5px;
    display: block;
    float: left;
}

.profile-pic {
    max-width: 200px;
    max-height: 200px;
    display: block;
}

.file-upload {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="profile-pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" />
<div class="upload-button">Upload Image</div>
<input class="file-upload" type="file" accept="image/*"/>

This code snippet is specific for images where its specified like this accept="image/*"/