Search code examples
javascripthtmljqueryfile-uploadcopy-paste

cut and paste a image file and upload it on form submit


I have code whereby I cut and paste an image in a div and it will upload the the image and store the file in a directory. I tried to change my code to upload the cut and paste file data on submit.

readastext seems to store the data in the hidden field. it also transfers the data on submit to the php file processor but no file is being created in the target directory. What am I doing wrong?

$(document).ready(function() {
  $('#pasteTarget').on('paste', function(e) {
    e.preventDefault();
    var data = e.originalEvent;
    
    if (data.clipboardData && data.clipboardData.items) {
      var items = data.clipboardData.items;
      for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          var file = items[i].getAsFile();
          var reader = new FileReader();
          reader.onload = function() {
            $("<input>").attr("type", "hidden").attr("name", "file[]").appendTo("form").val(reader.result);
          };
          reader.readAsText(file);
        }
      }
    }
  });
  
  $('#subfile').on('click', function(e) {
    var form = $('form')[0];
    var data = new FormData(form);
    
    $.ajax({
      type: "POST",
      url: 'postfileuploader.php',
      data: data,
      contentType: false,
      processData: false,
      cache: false,
      success: function(result) {
        console.log(result);
      },
      error: function(error) {
        console.log(error);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div style="width: 200px; height: 200px; background: grey" id="pasteTarget">
    Click and paste here.
  </div>
  <button type="button" name="sub" id="subfile" class="btn btn-primary">Create Tasks</button>
</form>
this is the postfileuploader.php

 <?php

echo $fileName = $_FILES['file'][0]['name'];
echo $fileType = $_FILES['file'][0]['type'];
echo $fileError = $_FILES['file'][0]['error'];
?>

this gives me an error Notice: Undefined index: file in F:\xampp745\htdocs\xxx\postfileuploader.php on line

an print_r($_POST) gives me

Array ( [file] => Array ( [0] =>file information code


Solution

  • FileReader.readAsText() reads the file as a plain text string. You should use FileReader.readAsDataURL() so the image data can be included as a value in the form. You can read more here: readAsDataURL