Question

I have an input tag like

<form id="myForm">
<!-- has lots of inputs above like username password etc -->
<input type="file" id="user_photo" name="user_photo" tabindex="6" size="6" class="" accept="jpeg|png|jpg|gif|PNG|JPEG|GIF|JPG" >

OnChange, I would want to upload an image through AJAX and save it in server. After saving, it should display in a preview div where I can use jCrop to crop as user wishes and save it again to the server (after cropping) when user clicks submit button.

If you have a better method please tell me.

inshort, I just want to trigger an ajax post request with the file contents and save it into my uploads folder without sending the rest of the form elements.

I use codeigniter. I have tried fileuploader by valum.. didnt give me the result.

Was it helpful?

Solution

Answer was stolen from here: Can i preview the image file who uploaded by user in the browser?

  1. Use the HTML5 File Api to load the image client side.
  2. Then use jCrop at the after loading the image into a tag.
  3. Then (I'm assuming) use jCrops onRelease method to do the Ajax call.
  4. That way its only one ajax call, and its already modified
<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">      
 function previewImage(input) {
    var preview = document.getElementById('preview');
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        preview.setAttribute('src', e.target.result);
         $('#preview').Jcrop({
            onRelease: yourAjaxFunctionToSubmitToServer
         });
      }
      reader.readAsDataURL(input.files[0]);
    } else {
      preview.setAttribute('src', 'placeholder.png');
    }
  }
</script>

Obviously this will need to be modified a bit to suit your needs, but you get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top