简体   繁体   English

将通过AJAX上传的二进制数据保存在PHP服务器上

[英]Save binary data uploaded through AJAX on PHP server

I've read a .png image file into an Array Buffer. 我已经将.png图像文件读入了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. 如AJAX所描述的那样,它被发布到PHP文件中。

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. 这些来自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: 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: HTML:

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

And PHP: 和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: 使用过的帖子:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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