将通过AJAX上传的二进制数据保存在PHP服务器上 [英] Save binary data uploaded through AJAX on PHP server

查看:145
本文介绍了将通过AJAX上传的二进制数据保存在PHP服务器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将.png图像文件读入了Array Buffer.

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);
        }

这已按照AJAX的说明发布到PHP文件中.

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);
  ?>

这些摘自Google的各种解决方案.该图像文件已创建,但不包含任何内容,因此无法打开.

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>

和PHP:

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

所有代码都在单个文件中,为了实现更好的格式,它分为三部分.

使用过的帖子:

  • Save binary data uploaded through AJAX on PHP server
  • file_get_contents("php://input") or $HTTP_RAW_POST_DATA...
  • fileReader.readAsBinaryString to upload files
  • Where and how do I set the correct encoding when uploading files using xhr

这篇关于将通过AJAX上传的二进制数据保存在PHP服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆