douchuose2514 2014-11-22 23:55
浏览 181
已采纳

将文件内容输出为二进制文件,如AJAX响应

OK the title doesn't give much a way so let me explain my very strange set-up.

Two servers are involved:

  • website: remote
  • localhost: local machine

The workflow is as follows:

  • The site calls localhost via cross-domain AJAX
  • In response localhost dynamically creates a ZIP file via PHP's ZipArchive lib
  • localhost conveys the raw data that comprises the archive as the AJAX response

The request is made and the archive is made - all good. The archive is openable, all good. What I'm stuck on now is how to convey that archive as the AJAX response, such that it can be "put together again" (à la Humpty Dumpty). When I do this currently (via file_put_contents()) it errors on opening, saying it's invalid. Currently I'm just outputting the archive's raw data:

echo file_get_contents('path/to/archive.zip');

This is fine, but sends garbled characters in the response. I don't know much about encoding and headers, so apologise if this seems obvious.

For the response, should I be looking to convert it to binary, or sending certain headers etc? I tried sending the multipart/form-data header, but no dice. Headers aren't my strong point.

Please note cURL is not an option in this scenario, else I'd be laughing.

  • 写回答

1条回答 默认 最新

  • dou7851 2014-11-23 00:21
    关注

    You have to read the zip file as a binary data with Blob javascript class.

    This is a code snippet from Mozilla documentation

    var oReq = new XMLHttpRequest();
    oReq.open("GET", "/myfile.png", true);
    oReq.responseType = "arraybuffer";
    
    oReq.onload = function(oEvent) {
      var blob = new Blob([oReq.response], {type: "application/octet-stream"}); //
      // you have nothing to do with the blob...
      // ...
    };
    
    oReq.send();

    Then send this file (blob) with POST method to your destination

    var oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.onload = function (oEvent) {
      // Uploaded.
    };
    
    oReq.send(blob); //the blob that you loaded

    you can read more in the documentation by Mozilla :https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)