简体   繁体   中英

Save binary data uploaded through AJAX on PHP server

I've read a .png image file into an Array Buffer.

var readSingleFile = function(e) {
          var file = e.target.files[0];
          if (!file) {
            return;
          }
          var reader = new FileReader();
          reader.onload = function(e) {
            var contents =new Int8Array(e.target.result);

            $.ajax({
                   url: 'saveBinaryData.php',
                   type: 'POST',
                   contentType: 'application/octet-stream', 
                   data: contents,
                   processData: false
                }); 
          };
          reader.readAsArrayBuffer(file);
        }

This is posted to a PHP file as the AJAX describes.

How do I convert this binary data to an image format?

My code so far:

<?php
 if($data=file_get_contents($_POST)){
   echo "Error! Data not read!";
   return;
  }

  $data = imagecreatefromstring($data);

  var_dump($data);

  file_put_contents("recentImage1.png", $data);
  ?>

These are taken from various solutions found in Google. The image file is created but does not hold any content and therefore cannot be opened.

This is simple working demo that saves the uploaded file:

JS:

<script src='https://code.jquery.com/jquery-2.2.3.min.js'></script>
<script>upload = function() {
    f = new FileReader();
    f.onload = function(e) {
        $.ajax({
            url: '?upload',
            type: 'POST',
            contentType: 'application/octet-stream;charset=UTF-8',
            data: e.target.result.split(",", 2)[1], //remove text header
            processData: false
        });
    };

    f.readAsDataURL($('input')[0].files[0]);
}
</script>

HTML:

<input type="file" />
<button onclick="upload()">Upload</button>

And PHP:

<?php
if (isset($_GET['upload'])) {
    $file = file_get_contents('php://input');
    file_put_contents('recentImage1.png', base64_decode($file));
}

All the code is in single file, just split into 3 parts for better formatting.

Used posts:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM