douxigai8757 2014-11-05 18:13
浏览 580
已采纳

通过JavaScript XHR2对象在PHP中发送ArrayBuffer

Here it is, I'm writing the new version of an AJAX library based on promises with XHR2 support (https://github.com/pyrsmk/qwest). I'm currently writing the unit tests and 95% of the library is now robust. Anyway, I need to verify that we can successfully retrieve an ArrayBuffer (XHR2 supports 'arraybuffer' response type) but how can I generate this ArrayBuffer with PHP? What protocol do I use? Base64?

I really have no idea how I should handle the whole thing...

EDIT : it seems that when I send an ArrayBuffer to PHP, the data is handled directly by the $_POST variable

  • 写回答

2条回答 默认 最新

  • duancunsu9209 2014-11-05 20:18
    关注

    Intro

    Well, you don't send an "ArrayBuffer". What you send is data and specify a format to make sense of that data. The client, then, can choose the best way to interpret it.

    So, an ArrayBuffer is just a generic fixed-length container for data (binary data) that enables you to create "views" of the underlying data using JavaScript typed arrays. The cool thing is that multiple views can be created from a single ArrayBuffer source.


    That being said, in your specific case, you can send binary data in PHP the same way you send any data in PHP.

    Example:

    server.php

    $filename = 'img.png';
    $fsize = filesize($filename);
    
    $handle = fopen($filename, "rb");
    $contents = fread($handle, $fsize);
    fclose($handle);
    
    header('content-type: image/png');
    header('Content-Length: ' . $fsize);
    
    echo $contents;
    

    or shorter

    $filename = 'img.png';
    
    header('content-type: image/png');
    header('Content-Length: ' . filesize($filename));
    
    readfile($filename);
    

    client.js

    var xhr = new XMLHttpRequest();
    
    xhr.open('GET', 'server.php', true);
    xhr.responseType = 'arraybuffer';
    
    xhr.onload = function(e) {
        var uInt8Array = new Uint8Array(this.response);
        console.log(uInt8Array);
    };
    
    xhr.send();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效