我试图从Unity客户端上传一个视频文件到python服务器,但当我尝试用 UnityWebRequest
在团结和 http
模块,但服务器接收到的视频文件无效,请问如何将Unity的视频文件通过Http上传至python?
我的问题是如何将Unity中的视频文件通过Http上传到python中?
这是我在Unity中的代码。
IEnumerator StartUploadCoroutine()
{
// Show a load file dialog and wait for a response from user
yield return FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load");
isOpen = false;
// Upload File to movie server
if (FileBrowser.Success)
{
StreamReader reader = new StreamReader(FileBrowser.Result);
StartCoroutine(UploadCoroutine(reader)); // upload file to server;
}
}
/* Upload the chosen video file to the movie server */
IEnumerator UploadCoroutine(StreamReader reader)
{
UnityWebRequest www = UnityWebRequest.Post(videoPlayerManager.GetServerIp() + ":" + port.ToString(), reader.ReadToEnd());
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
这是我的Python代码
from http.server import BaseHTTPRequestHandler, HTTPServer
class HandleRequests(BaseHTTPRequestHandler):
def do_POST(self):
'''Reads post request body'''
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
self.send_response(200)
self.end_headers()
outF = open("myOutFile.mp4", "wb")
outF.write(body)
host = "127.0.0.1"
port = 9999
HTTPServer((host, port), HandleRequests).serve_forever()
我想明白了,多亏了> MohammadReza Arashiyan。
我的问题是将文件从Unity中以字符串的形式发送,而不是以字节数组的形式发送.我已经将我的python代码改为Flask服务器,这样我就可以很容易地从post请求中获取文件,我最终得到了这些代码。
这是我在Unity中的代码
IEnumerator StartUploadCoroutine()
{
// Show a load file dialog and wait for a response from user
yield return FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load");
isOpen = false;
// Upload File to movie server
if (FileBrowser.Success)
{
StartCoroutine(UploadCoroutine(FileBrowser.Result)); // upload file to server;
}
}
/* Upload the chosen video file to the movie server */
IEnumerator UploadCoroutine(string filePath)
{
WWWForm form = new WWWForm();
form.AddBinaryData("vidFile", File.ReadAllBytes(filePath));
UnityWebRequest www = UnityWebRequest.Post(videoPlayerManager.GetServerUrl(), form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
这是我的Python代码
import os
from flask import Flask, request, send_from_directory
from gevent.pywsgi import WSGIServer
IP = "127.0.0.1"
PORT = 9999
# set the project root directory as the static folder
app = Flask(__name__)
@app.route('/', methods=['POST'])
def DownloadFile():
# request.form to get form parameter
vidFile = request.files["vidFile"].read()
outF = open("myOutFile.mp4", "wb")
outF.write(vidFile)
return ''
if __name__ == "__main__":
http_server = WSGIServer((IP, PORT), app)
http_server.serve_forever()