2

I try this reference : https://github.com/blueimp/JavaScript-Load-Image

I try like this : https://jsfiddle.net/oscar11/gazo3jc8/

My code javascript like this :

$(function () {
  var result = $('#result')
  var currentFile

  function updateResults (img, data) {
    var content
    if (!(img.src || img instanceof HTMLCanvasElement)) {
      content = $('<span>Loading image file failed</span>')
    } else {
      content = $('<a target="_blank">').append(img)
        .attr('download', currentFile.name)
        .attr('href', img.src || img.toDataURL())

      var form = new FormData();
      form.append('file', currentFile);

       $.ajax({
                    url:'response_upload.php',
                    type:'POST',
                    data:form,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        console.log(response);
                    },
                    error: function () {
                        console.log(error)
                    },
                });
    }
    result.children().replaceWith(content)
  }

  function displayImage (file, options) {
    currentFile = file
    if (!loadImage(
        file,
        updateResults,
        options
      )) {
      result.children().replaceWith(
        $('<span>' +
          'Your browser does not support the URL or FileReader API.' +
          '</span>')
      )
    }
  }

  function dropChangeHandler (e) {
    e.preventDefault()
    e = e.originalEvent
    var target = e.dataTransfer || e.target
    var file = target && target.files && target.files[0]
    var options = {
      maxWidth: result.width(),
      canvas: true,
      pixelRatio: window.devicePixelRatio,
      downsamplingRatio: 0.5,
      orientation: true
    }
    if (!file) {
      return
    }
    displayImage(file, options)
  }

  // Hide URL/FileReader API requirement message in capable browsers:
  if (window.createObjectURL || window.URL || window.webkitURL ||
      window.FileReader) {
    result.children().hide()
  }

  $('#file-input').on('change', dropChangeHandler)
})

If I uploaded the image, the image saved in the folder still does not use the image that is in its orientation set. I want when I upload a picture, the image stored in the folder is the image that has been set its orientation

It seems that the currentFile sent via ajax is the unmodified currentfFile. How do I get the modified currentFile?

2
  • Hi bro I found you a solution see my second answer. Commented Aug 15, 2017 at 17:38
  • @Novice, Okay bro. Thanks a lot Commented Aug 15, 2017 at 19:29

2 Answers 2

2

After some researching little bit I found the solution thanks to this great plugin https://github.com/blueimp/JavaScript-Canvas-to-Blob . ( canvas-to-blob.js )

This plugin will convert your canvas to a Blob directly server would see it as if it were an actual file and will get the new(modified) file in you $_FILES array. All you need is call toBlob on the canvas object (img). After that you would get your blob which you then can send in FormData. Below is your updated updateResults() function

function updateResults (img, data) {
  var content
  if (!(img.src || img instanceof HTMLCanvasElement)) {
    content = $('<span>Loading image file failed</span>')
  } 
  else 
  {
       content = $('<a target="_blank">').append(img)
      .attr('download', currentFile.name)
      .attr('href', img.src || img.toDataURL())

      img.toBlob(
           function (blob) {
               var form = new FormData();
               form.append('file', blob, currentFile.name);

               $.ajax({
                  url:'response_upload.php',
                  type:'POST',
                  data:form,
                  processData: false,
                  contentType: false,
                  success: function (response) {
                    console.log(response);
                  },
                  error: function () {
                    console.log(error)
                  },
               });

           },'image/jpeg'   
      );
      result.children().replaceWith(content);
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I had try it. And seems it works. I want to ask. So it's a collaboration between 2 plugins? JavaScript-Load-Image plugin and JavaScript-Canvas-to-Blob
The visible code seems it can only upload jpeg images. Whether gif, png, jpg can also uploaded?
Ye they work in collabration . For png image types replace "image/jpeg" to "image/png" .You can get image type dynamically if you use currentFile.type there
Okay. Thanks a lot. Your answer really helped me
what is the content of the response_upload.php ?
0

You want to change some things about image (dimensions, roataion etc) and upload it on to the server but the problem here is that ImageLoad plugin will give the modified image as an canvas means it won't modify the original file selected in <input type="file" id="file-input">. Since you are sending the file input object in form.append('file', currentFile); your modified file wont get sent but just the original

How to fix?

This is particularity hard you (or plugin) cannot modify anything on <input type="file" id="file-input"> due to browser restrictions neither you can send canvas directly to the server so the only way (used and works great) is to send the data URI of the image as a regular text and then decode it on the server, write it to a file.You might also want to send the original file name since a data URI is pure content and doesn't hold file name

Change

  form.append('file', currentFile);

To

  form.append('file', img.toDataURL() );        // data:image/png;base64,iVBO ...
  form.append('file_name',  currentFile.name ); // filename 

PHP

  $img_data=substr( $_POST['file'] , strpos( $_POST['file'] , "," )+1); 
  //removes preamble ( like data:image/png;base64,)
  $img_name=$_POST['file_name'];

  $decodedData=base64_decode($img_data);

  $fp = fopen( $img_name , 'wb' );
  fwrite($fp, $decodedData);
  fclose($fp );

Good luck!

10 Comments

In php I add this : echo '<pre>';print_r($_POST['file']);echo '</pre>';die(); to check the result. But it was too long and did not show anything
If I try this : echo '<pre>';print_r($_FILES);echo '</pre>';die();, the result empty array like this : <pre>Array ( ) </pre>
yes $_POST['file'] will not show the image but instead its encoded form so you have to decode it using base64_decode, don't use $_FILES it is supposed to be empty you may add and extra form.append('file', currentFile); but that would give only the original file. So you have to use $_POST['file'] and decode it
Okay. I have followed your way. Then how can I get the data file to be stored in the folder? I tried echo '<pre>';print_r($fp);echo '</pre>';, the result : <pre>Resource id #3</pre>. It is not a data file
I want the result like this : Array ( [file] => Array ( [name] => chelsea.jpeg [type] => image/jpeg [tmp_name] => C:\xampp\tmp\php1E31.tmp [error] => 0 [size] => 1244449 ) ) If the result is like that, it can be stored in the folder
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.