douxing2652 2016-04-27 09:28
浏览 72

将二进制数据发送到服务器

I create an array buffer containing some data:

var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);
for (var i = 0; i < longInt8View.length; i++) {
    longInt8View[i] = i % 255;
}

And I send it so a server via POST:

if (window.XMLHttpRequest) {
    var xmlhttp = new XMLHttpRequest();
} else {
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        action(xmlhttp.responseText);
    }
};
xmlhttp.open("POST", 'http://somedomain.com:8080', true);
xmlhttp.send(myArray);
var action = function (response) {
    console.log(response);
};

I now want to receive these binary data in go code, and do something with it. How can I do this?

package main

import (
        "fmt"
        "net/http"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Headers", "*")
        w.Header().Set("Content-Type", "text/plain")
        fmt.Fprintf(w, "%s", r.Body)
}

func main() {
        http.HandleFunc("/", handleRequest)
        http.ListenAndServe(":8080", nil)
}

I can see a reference to a memory block inside the body, but how do I get this specificaly?

  • 写回答

1条回答 默认 最新

  • doushi1974 2016-04-27 09:31
    关注

    Don't send binary data over HTTP protocol. Convert them in Base64. Send them as a normal string. Decode them from Base64 to binary on the server side.

    To convert a binary data to base64 you can use the function btoa

    评论

报告相同问题?

悬赏问题

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