Search code examples
javascriptjqueryhtmlimage-uploadingbeego

get image and upload/save it in server location


I have an beego application in which i have a requirement of uploading a image from client for to server location.

//Till now I have tried the following script
$("#fileupload").on("click",function(){
  $("#my_file").click();
  userImage = document.getElementById('fileupload');
  imgData = getBase64Image(userImage);
  localStorage.setItem("imgData", imgData);
});
<!--Html where i have kept option for image upload-->
<ul>
  <li style="margin-top:5px;">  .Hii vijay  </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>

using this script, when i click on empty image(click here to add) it is displaying a browse file option.After selecting the image no action taking place. My requirement is on selection of image from browse option, the selected image should be saved in server location.


Solution

  • See additional notes on bottom...

    Relevant template markup:

    <input type='file' id="imageInput" name="imageInput" accept="image/*"/>
    

    Relevant JavaScript:

    $('#imageInput').change(function(){
        var frm = new FormData();
        frm.append('imageInput', input.files[0]);
        $.ajax({
            method: 'POST',
            address: 'url/to/save/image',
            data: frm,
            contentType: false,
            processData: false,
            cache: false
        });
    });
    

    Beego controller handling the upload:

    // relevant code
    // file upload handling
    file, header, er := this.GetFile("imageInput")
    if file != nil {
        // some helpers 
        // get the extension of the file  (import "path/filepath" for this)
        extension := filepath.Ext(header.Filename)
        // full filename
        fileName := header.Filename
        // save to server`enter code here`
        err := this.SaveToFile("imageInput", somePathOnServer)
    }
    

    JavaScript:

    Once the change event fires a new FormData object is being created. The file data is being appended to the form object, finally the code executes a POST request using Ajax.

    Beego controller:

    By using the .GetFile() method with "imageInput" as argument which is the HTML input control element you can get the file data.

    By using the .SaveToFile() method with "imageInput" and a path as arguments, you can save the file to the server.

    Note this refers to the controller. I create my Beego controllers using func (this *MainController) ControllerName ()