PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

[FIXED] How to upload an image to server on change

 October 11, 2022     codeigniter, gd, jcrop, jquery, php     No comments   

Issue

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.


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.



Answered By - WiR3D
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing