4

I am trying to upload a image to Database using Javascript on client and PHP on server.

  • first image is selected from the gallery.
  • after zooming and cropping the image is passed to database

The Problem is when iam trying to submit the cropped image value is not passed to the php the actual uploaded input "File" Value is Being Passed, but i need the cropped areas value to be passed to PHP.

For testing purpose if all the js are required i can provide it.

Upload Image snip

Js: This Crops the image

$(function() {
        $('.image-editor').cropit({
          exportZoom: 1.25,
          imageBackground: true,
          imageBackgroundBorderWidth: 40,

    });

    $('.export').click(function() {
      var imageData = $('.image-editor').cropit('export');
      window.open(imageData);
    });
  });

HTML:

 <form id="uploadForm" class="image-editor">
      <input type="file" class="cropit-image-input">
      <!-- .cropit-image-preview-container is needed for background image to work -->
      <div class="cropit-image-preview-container">
        <div class="cropit-image-preview"></div>
      </div>
      <div class="image-size-label">
        Resize image
      </div>
      <input type="range" class="cropit-image-zoom-input">
      <input type="submit" class="export">Export</input >
    </form>

Ajax: ajax sends the data to php

$(document).ready(function (e) {

    $("#uploadForm").on('submit', (function (e) {
        e.preventDefault();
        $.ajax({
            url: "upload.php",
            type: "POST",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                $("#targetLayer1").html(data);
            },
            error: function () {}
        });
    });
});

PHP:

 if(count($_FILES) > 0) {
        if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
           $mysl = mysqli_connect("localhost", "root", "root","test");

            $imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
            $imageProperties = getimageSize($_FILES['userImage']['tmp_name']);

            $sql = "UPDATE output_images SET imageType  ='{$imageProperties['mime']}',imageData= '{$imgData}' WHERE imageId='16'";
            $current_id = mysqli_query($mysl,

$sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());;
            if(isset($current_id)) {
                echo "done";
            }
        }
        }
  • Why not just send the new dimensions as values and crop it in php? – Evadecaptcha Jul 23 '15 at 14:30
  • @EvadeCaptcha , Good Point but the same process should be repeated in PHP as a PHP code right?? –  Jul 23 '15 at 14:32
  • If it were me, I would have jQuery create the dimensions from the interface and not actually crop the image on the frontend (just make it appear so), then send those dimensions and the image to the php script. Then store the image in a tmp folder, and use the dimensions to crop out a new image to be stored in the permanent location. However, somebody may answer with a better way, as I've never dealt with image cropping before. – Evadecaptcha Jul 23 '15 at 14:50
  • Sound interesting am new to this what are the benefits if i do it as u say i have no issue to do it as u say y am asking is am scared if the image size is more than 2mb the same data is wasted on both the side as on client to send the image and on server receiving, Plz if u can elaborate ur ans a bit more i can understand how ever i am doing this first time to –  Jul 23 '15 at 15:05
  • You're right that it will be sending unnecessary data, since you only need a portion of the image, so whether or not that overhead is worth it would depend on the amount of traffic the server handles, and how large the image is allowed to be. That brought to light, if you can find a way to crop it on the front end, then send the image back, I would do that. I just don't know how to accomplish creating a new image on the frontend. – Evadecaptcha Jul 23 '15 at 15:21
  • I suspect that the issue is that the `imageData` is not a part of the form data. I would build your own `data:`. I did something similar when posting a canvas via Ajax to PHP. Will post an answer. – Twisty Jul 23 '15 at 16:19
  • What i do in these cases is that, i first upload the image, then show another screen for cropping, take the css dimensions and crop the image using php. That reduces the complexity greatly. – Gogol Jul 24 '15 at 06:38
  • can u plz share the same ??? –  Jul 24 '15 at 06:48

1 Answers1

1

First, take a look at this: Can I pass image form data to a PHP function for upload?

I think the issue is here: var imageData = $('.image-editor').cropit('export');. Since this new image is never a part of the form, there is no way to pass it via AJAX. In your JS/JQuery, I would advise:

var imageData = '';
$(function() {
    $('.image-editor').cropit({
        exportZoom: 1.25,
        imageBackground: true,
        imageBackgroundBorderWidth: 40,
    });

    $('.export').click(function() {
        imageData = $('.image-editor').cropit('export');
        window.open(imageData);
    });
});
$(document).ready(function (e) {
    $("#uploadForm").on('submit', (function (e) {
        e.preventDefault();
        var fd = new FormData(this);
        fd.append( imageData, file );
        $.ajax({
            url: "upload.php",
            type: "POST",
            data: fd,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                $("#targetLayer1").html(data);
            },
            error: function () {}
        });
    });
});

EDIT

In your example, you never defined a name or id attribute for your input, so there would be no way for PHP to index the $_FILES global. Could try $_FILES[0]. I would advise assigning that in your form or when you post it.

You can adjust the myFormData.append(name, file, filename);. So it would be:

fd.append('crop-image', imageData, 'crop-image.jpg');

Then in PHP, you call it using $_FILES['crop-image']. If you want to pass the file name from the form:

$(document).ready(function (e) {
    $("#uploadForm").on('submit', (function (e) {
        e.preventDefault();
        var fd = new FormData(this);
        var origFileName = $("input[type='file']").val();
        var startIndex = (origFileName.indexOf('\\') >= 0 ? origFileName.lastIndexOf('\\') : origFileName.lastIndexOf('/'));
        var filename = origFileName.substring(startIndex);
        if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0){
            filename = filename.substring(1);
        }
        var cropFileName = "crop-" + filename;
        fd.append('crop-image' imageData, cropFileName );
        $.ajax({
            url: "upload.php",
            type: "POST",
            data: fd,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                $("#targetLayer1").html(data);
            },
            error: function () {}
        });
    });
Community
  • 1
  • 1
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Thanks For ur answer was expecting the same but i have a quick question what about on server side how can i receive this image and save in database??? –  Jul 24 '15 at 06:28
  • if i add the upload script to it then the crop area displays nothing..:( –  Jul 24 '15 at 07:05
  • You might try forcing it back into the form elements: http://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload – Twisty Jul 24 '15 at 15:15
  • See Edits to answer. I do not understand what you mean by "the crop area displays nothing" – Twisty Jul 24 '15 at 15:52