Code Monkey home page Code Monkey logo

Comments (7)

jacojvv-dev avatar jacojvv-dev commented on September 28, 2024

Hello, I was also using php to create a file upload. I modified the code that was in the original page about server side implementation.

Mine also 'stopped' when it reached the end.

My code might not be the best, I am still a junior programmer and I have much to learn.

I have not yet implemented crop and rotate, but will soon.

Here is all the code I have in my content-tools.js file.

This was modified from the upload.

function imageUploader(dialog) {
  var image, xhr, xhrComplete, xhrProgress;

  // Set up the event handlers


  dialog.bind('imageUploader.cancelUpload', function () {
    // Cancel the current upload

    // Stop the upload
    if (xhr) {
      xhr.upload.removeEventListener('progress', xhrProgress);
      xhr.removeEventListener('readystatechange', xhrComplete);
      xhr.abort();
    }

    // Set the dialog to empty
    dialog.state('empty');
  });

  dialog.bind('imageUploader.clear', function () {
    // Clear the current image
    dialog.clear();
    image = null;
  });

  //IMAGE UPLOADER FILEREADY START ----------------------------------------------------
  dialog.bind('imageUploader.fileReady', function (file) {

    // Upload a file to the server
    var formData;

    // Set the dialog state to uploading and reset the progress bar to 0
    dialog.state('uploading');
    dialog.progress(0);

    // Build the form data to post  to the server
    formData = new FormData();
    formData.append('image', file);

    //AJAX CALL START -------------------------------------------------------------------
    $.ajax({
      xhr: function() {
        //Instantiate XHR
        var xhr = new window.XMLHttpRequest();

        //Add Progress Event Listener
        xhr.upload.addEventListener("progress", function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);
            console.log(percentComplete);
            dialog.progress(percentComplete);

            if (percentComplete === 100) {
              //Upload Is Complete
            }    
          }
        }, false);    
        return xhr;
      },
      url: 'assets/imagePost.php',
      data: formData,
      cache: false,
      type: 'POST',
      contentType: false,
      processData: false,
      success: function(result) {

        // Unpack the response (from JSON)    
        response = JSON.parse(result);

        // Store the image details
        image = {
          size: response.size,
          url: response.url
        };

        // Populate the dialog
        dialog.populate(image.url, image.size);     

        // Clear the request
        xhr = null
        xhrProgress = null
        xhrComplete = null  

      }
    });
    //AJAX CALL END ---------------------------------------------------------------------
  });
  //IMAGE UPLOADER FILEREADY END --------------------------------------------------------

  dialog.bind('imageUploader.save', function () {
        var crop, cropRegion, formData;

        // Set the dialog to busy while the rotate is performed
        dialog.busy(true);

        // Build the form data to post to the server
        formData = new FormData();
        formData.append('url', image.url);

        // Set the width of the image when it's inserted, this is a default
        // the user will be able to resize the image afterwards.
        formData.append('width', 600);

        // Check if a crop region has been defined by the user
        if (dialog.cropRegion()) {
            formData.append('crop', dialog.cropRegion());
        }

    //AJAX CALL START -------------------------------------------------------------------
    $.ajax({
      url: 'assets/imageSave.php',
      data: formData,
      cache: false,
      type: 'POST',
      contentType: false,
      processData: false,
      success: function(result) {   

            // Free the dialog from its busy state
            dialog.busy(false);

          // Unpack the response (from JSON)
          var response = JSON.parse(result);

          // Trigger the save event against the dialog with details of the
          // image to be inserted.
          dialog.save(
            response.url,
            response.size,
            {
                'alt': response.alt,
                'data-ce-max-width': response.size['width']
            });

            // Clear the request
            xhr = null
            xhrComplete = null
      }
    });
    //AJAX CALL END ---------------------------------------------------------------------
    });

}

Then Modify The Code On Lines 8502 - 8504 To Look Like This

          imageAttrs.height = imageSize['height'];
          imageAttrs.src = imageURL;
          imageAttrs.width = imageSize['width'];

Then in my imagePost.php I have a basic file uploaded (Which I kind of copied and pasted from W3 :) )

<?php

    $postData = $_FILES;

    $target_dir = "Lessons/1/images/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["image"]["size"] > 1500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {

            $arr = array('size' => $_FILES["image"]["size"], 'url' => 'http://localhost:8080/ContentBuilder/assets/Lessons/1/images/'.$_FILES["image"]["name"].'');
            echo json_encode($arr);

        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

?>

And Then Finally In imageSave.php

<?php

    $items = list($width, $height) = getimagesize($_POST['url']);

    $arr = array('url' => $_POST['url'], 'width' => $_POST['width'], 'crop' => $_POST['crop'],
     'alt'=> "Image", 'size' => array('width' => $items[0], 'height' => $items[1] ));

    echo json_encode($arr);
?>

I hope I was of help, If you can see a way in which I can improve the code, please tell me.

from contenttools.

anthonyjb avatar anthonyjb commented on September 28, 2024

Hi @laurent-d and @jacojvv-dev - I'm definitely not a PHP expert but I'll try to help.

If the progress bar stopped at 100% then my guess would be that an error occurred before or during the call to dialog.populate as this changes the state of the dialog and hides the progress bar. The error should be visible in the console output, or if the server is failing tor return a 200 response then under the network tab on Chrome or FF you should be able to see details of the failed response. Can you post any error information you can see please.

from contenttools.

anthonyjb avatar anthonyjb commented on September 28, 2024

@laurent-d specific to your original question, yes there are values that need to be returned once the file has been uploaded. Specifically you need to return the URL and size(width, height) of the image uploaded, if you're using the tutorial code from here http://getcontenttools.com/tutorials/handling-image-uploads then size should be specified as an array of the form [width, height] e.g [400, 300].

from contenttools.

guillaumepiot avatar guillaumepiot commented on September 28, 2024

@jacojvv-dev as @andyjbgm mentioned, the server response data needs to contain a size array, representing the width and height of the image.

At the moment, your imagePost.php script (which is the one called on 'fileready') returns the file size of the image as opposed to its dimensions:

$arr = array('size' => $_FILES["image"]["size"], 'url'=>''...");

My recommendation would be to return the same array format as imageSave.php is returning, eg:

$items = list($width, $height) = getimagesize($_POST['url']);
$arr = array('url' => $_POST['url'], 'size' => array($items[0], $items[1]));

Of course, the javascript console is the best starting point to identify potential issue with the UI.

from contenttools.

laurent-d avatar laurent-d commented on September 28, 2024

Thanks @jacojvv-dev, @anthonyjb and @guillaumepiot for your help, i will try all you tell me in a day.
and tell you what it happen. My script doesn't return these two vars... Work in progress

from contenttools.

jacojvv-dev avatar jacojvv-dev commented on September 28, 2024

Thanks @guillaumepiot I think when I was writing the code I was so focused on getting it to work that I did not even consider what they wanted returned. I am going to implement these changes as soon as I can.

Thank You.

from contenttools.

guillaumepiot avatar guillaumepiot commented on September 28, 2024

@jacojvv-dev no worries, just let me know how it goes.

from contenttools.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.