首页 > 解决方案 > UnityWebRequest 字节数组

问题描述

我正在尝试通过网络摄像头捕获的每一帧,使用要在 NodeJS API 中处理的发布请求发送图像字节。

使用此代码:

Debug.Log(imageBytes.Length); //Prints a number
    Debug.Log(imageBytes); //Prints the array type (?)
    Debug.Log(imageBytes[1]); //Prints the byte

    UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        UploadHandlerRaw handler = new UploadHandlerRaw(imageBytes);
        handler.contentType= "application/x-www-form-urlencoded";
        www.uploadHandler = handler;
        Debug.Log(www.uploadHandler.data[1]);
        www.downloadHandler = new DownloadHandlerBuffer();

        yield return www.SendWebRequest();
        string jsonResponse = www.downloadHandler.text;
        Debug.Log(jsonResponse);

但是,当我console.log在 API 中执行它时,req.body它会打印

{}

. 显然,数据不是由UnityWebRequest.

对此有什么想法吗?

标签: c#node.jsunity3d

解决方案


我找到了一种让这个工作的方法。

需要将Unity中的代码改成:

    using (UnityWebRequest www = UnityWebRequest.Post(url, webForm))
            {
        www.SetRequestHeader("Content-Type", "text/html");
        www.uploadHandler = new UploadHandlerRaw(imageBytes);
        www.uploadHandler.contentType = "text/html";
        www.downloadHandler = new DownloadHandlerBuffer();
        yield return www.SendWebRequest();
            }

在 Node.JS 中:

app.use(cors());
var options = {
    inflate: true,
    limit: '3000kb',
    type: 'text/html'
  };
app.use(bodyParser.raw(options));

推荐阅读