Get image and save in storage

679 views Asked by At

I have an web page which is a profile viewing page. Here I have an blank image. On click of this image I am able to prompt browse image option. But I don't know how to save the image into storage. Here is my code:

<div class="profileImage" >
    <ul>
        <li style="margin-top:5px;">  
            .Hii  
        </li>
        <li>
            <input type="file" id="my_file" style="display: none;" />
        </li>
        <li>
            <img id="fileupload" name="filetoupload" src="../../static/img/img.png">
        </li>
    </ul>
</div>
$(document).ready(function(){
    $("#fileupload").on("click", function() {
        $("#my_file").click();
    }

I tried this below jQuery to save image but is was of no use.

$(document).ready(function(){
    $("#fileupload").on("click",function(){
        $("#my_file").click();
        userImage = document.getElementById('fileupload');
        imgData = getBase64Image(userImage);
        localStorage.setItem("imgData", imgData);
    });    
});

My requirement is I should be able to save the image from clicking add image i.e img.png in my code. I am using beego as web framework, but i will be happy if this get solved in jQuery or javascript.

1

There are 1 answers

10
Roko C. Buljan On BEST ANSWER

jsBin demo

// https://stackoverflow.com/a/17711190/383904
function readImage() {
  if ( this.files && this.files[0] ) {
    var FR= new FileReader();
    FR.onload = function(e) {
      localStorage.setItem("imgData", event.target.result); // Send to Localstorage
    };       
    FR.readAsDataURL( this.files[0] );
  }
}

$(document).ready(function(){
  $("#fileupload").on("click",function(){
    $("#my_file").click().change( readImage );
  });   
});

To save that image on server you'll need to send that data to PHP.
PHP can than convert your base64 string to an image.

Otherwise, why not simply send that image using AJAX to a PHP script that will put it inside a server folder?

Send Image to server using File input type
https://stackoverflow.com/a/17711190/383904