我正在尝试使用网络摄像头捕获的每个帧发送图像字节,使用在NodeJS API中处理的post请求。
使用此代码:
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
发送。
有什么想法吗?
您使用错误的内容类型来存储二进制数据。如果您使用WWWForm类,它将自动将此标头设置为multipart / form-data。试试这段代码:
var wwwForm = new WWWForm();
wwwForm.AddBinaryData ("image", imageBytes, "imagedata.raw");
var request = UnityWebRequest.Post (url, wwwForm);
yield return request.SendWebRequest ();
我找到了一种方法让这个工作。
需要将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));
我几个月前尝试了一些新的webrequest类,我在向服务器发布数据时遇到了类似的问题,然后我切换回旧的www类来处理它,它就像一个魅力。