unity+上传数据到服务器(string、对象、文件)
1.string方式
首先去下载LitJson.dll,放在Plugins 目录下;
LitJson可以从下面的地址获得:http://download.csdn.net/detail/h570768995/9373927
然后我们定义json格式,比如我们需要如下格式:
{"intValue":345,"longValue":345679876,"stringValue":"xiaoxian","byteValue":'v',"doubleValue":345.87}
public class MessageJson { public int intValue; public long longValue; public string stringValue; public byte byteValue; public double doubleValue; }
然后在方法中声明该类,接着将其映射为Json格式:
MessageJson msgJson = new MessageJson(); msgJson.intValue = 20; msgJson.longValue = 10000000000000L; msgJson.stringValue = "chenhao"; msgJson.byteValue = (byte)msgJson.intValue; msgJson.doubleValue = 3153456.125651; string jsonDataPost = JsonMapper.ToJson(msgJson);
如此将该数据传送出去:
WWW www = new WWW("http://192.168.1.192:18080/test",Encoding.UTF8.GetBytes(jsonDataPost));
接着等待数据,并可以打印出来:
while(!www.isDone) { Debug.Log("wait"); } yield return www; if(www.error!=null) { Debug.LogError(www.error); } else { Debug.Log(www.text); //取数据1 MessageJson msgJsonRecieve = JsonMapper.ToObject<MessageJson>(www.text); Debug.Log(msgJsonRecieve.intValue); Debug.Log(msgJsonRecieve.longValue); Debug.Log(msgJsonRecieve.stringValue); Debug.Log(msgJsonRecieve.byteValue); Debug.Log(msgJsonRecieve.doubleValue); //取数据2 JsonData jsonData = JsonMapper.ToObject(www.text); if (jsonData["stringValue"] != null) { Debug.Log(jsonData["stringValue"].ToString()); }
JsonMapper映射可以无视排序问题,它只看“键值对”中的键。
/// <summary> /// 发送整体string,由于数据量比较大,目前55M,所以弃用 /// </summary> /// <returns></returns> IEnumerator UpLoadData() { if (OfflineDevicesDic != null && OfflineDevicesDic.Count != 0) { //foreach(var item in OfflineDevicesDic.Values) //{ // foreach (var item1 in item.offlinePhotos) // { // Debug.LogError(item1.stepId+"______"+item1.base64str); // } //} //总体信息 offlineGameStatusJson = new OfflineGameStatus(); offlineGameStatusJson.sceneId = ARGameJsonDateHandle.ARGameJsonDateHandleInstance.CurrentTasks.sceneId; offlineGameStatusJson.staffNumber = ARGlobalData.SuccessScanUserID; offlineGameStatusJson.TotalScore = ARScroingTimeManager.ARScroingTimeManagerInstance.TotalPointTemp; offlineGameStatusJson.SkipScanScore = ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanGrade; offlineGameStatusJson.TotalTime = ARScroingTimeManager.ARScroingTimeManagerInstance.TotalScroingTime; offlineGameStatusJson.SkipScanNumber = ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanNum; offlineGameStatusJson.offlineDevices = new OfflineDevices[OfflineDevicesDic.Values.Count]; OfflineDevicesDic.Values.CopyTo(offlineGameStatusJson.offlineDevices, 0);//将OfflineDevicesDic.Values复制到(offlineGameStatusJson.offlineDevices数组中,起始位置为0) // OfflineUpLoadJson = JsonMapper.ToJson(offlineGameStatusJson);//保存本地中文乱码 // string JsonDataPost = JsonUtility.ToJson(offlineGameStatusJson);//保存本地中文不乱码 string JsonDataPost = JsonMapper.ToJson(offlineGameStatusJson);//保存本地中文不乱码 // string savePath1 = Application.persistentDataPath + "/" + name + "_" + ARGlobalData.SuccessScanUserID + ".txt"; ////File.WriteAllText(savePath, LocalJson); // strTest.Add(JsonDataPost); // File.WriteAllLines(savePath1, (string[])strTest.ToArray(typeof(string))); WWW www = new WWW(ARGlobalData.NewConfigurePathStr + "/TPlant-inspect/api/inspect/uploadInspectionResult", Encoding.UTF8.GetBytes(JsonDataPost)); while (!www.isDone) { Debug.Log("wait"); } yield return www; if (www.error != null) { Debug.LogError(www.error); IsOfflineUploadDataSuccess = false; } else { Debug.LogError(www.text); //取数据1 OfflineGameStatus OfflineGameStatusref = JsonMapper.ToObject<OfflineGameStatus>(www.text); Debug.LogError(OfflineGameStatusref.staffNumber); IsOfflineUploadDataSuccess = true; //取数据2 //JsonData jsondata = JsonMapper.ToObject(www.text); //if(jsondata["sceneId"]!=null) //{ // Debug.LogError(jsondata["sceneId"].ToString()); //} } } }
注:https://blog.csdn.net/h570768995/article/details/50386935
2.对象(之前按步骤上传的方法PA)
/// <summary> /// WWWForm上传json,和单步上传相同,由于上传到服务器的数据会成一堆,后台不好解析,暂时弃用 /// </summary> public void NewUpLoadData() { if (OfflineDevicesDic != null && OfflineDevicesDic.Count != 0) { WWWForm inspectResult = new WWWForm(); inspectResult.AddField("sceneId", ARGameJsonDateHandle.ARGameJsonDateHandleInstance.CurrentTasks.sceneId); inspectResult.AddField("staffNumber", ARGlobalData.SuccessScanUserID); inspectResult.AddField("TotalScore", ARScroingTimeManager.ARScroingTimeManagerInstance.TotalPointTemp); // inspectResult.AddField("SkipScanScore", ARGlobalData.SkipScanScore);//2021.10.15注释 inspectResult.AddField("SkipScanScore", ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanGrade); inspectResult.AddField("TotalTime", ARScroingTimeManager.ARScroingTimeManagerInstance.TotalScroingTime); inspectResult.AddField("SkipScanNumber", ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanNum); foreach (var item in OfflineDevicesDic.Values) { inspectResult.AddField("taskId",item.taskId); inspectResult.AddField("actionId", item.actionId); inspectResult.AddField("deviceId", item.deviceId); if (item.offlineSteps.Length > 0 && item.offlineSteps != null) { foreach (var item1 in item.offlineSteps) { inspectResult.AddField("stepId", item1.stepId); inspectResult.AddField("opTime", item1.opTime); inspectResult.AddField("opResult", item1.opResult); } } inspectResult.AddField("SingleDeviceCheckScore", item.taskId); if(item.offlinePhotos.Length>0&& item.offlinePhotos!=null) { foreach (var item2 in item.offlinePhotos) { Debug.LogError(item2.base64str); inspectResult.AddField("stepId", item2.stepId); inspectResult.AddField("base64str", "1111"); } } } // Debug.LogError("inspectResult: "+ inspectResult.data.ToString()); OnSendPost(ARGlobalData.NewConfigurePathStr + "/TPlant-inspect/api/inspect/uploadInspectionResult", inspectResult); } }
public void OnSendPost(string url, WWWForm wForm) { StartCoroutine(SendPost(url, wForm)); } IEnumerator SendPost(string url, WWWForm wForm) { WWW postDate = new WWW(url, wForm); // Debug.LogError(postDate.text); //Debug.LogError(postDate); yield return postDate; if (postDate.error != null) { Debug.LogError(postDate.error); } else { Debug.Log(postDate.text); } }
3.Unity使用UnityWebRequest上传文件到服务器的简单实现流程
前言
我在以前的项目中写过有关上传图片到服务器的功能,但是没有写过上传其他类型的文件到服务器上的功能。今天为了实现一个上传gif图片的功能,我在网上查找资料,找到了一种使用UnityWebRequest上传文件的方法。这个方法真是太有用处了,可以说是什么文件都通用,于是我在这里赶紧记录一下,方便以后使用。
实现步骤
1.实现步骤很简单,以下是我自己很据网上的资料写的脚本,完成后将此脚本挂载到场景中的物体上,代码如下所示:
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; public class UpGifManager : MonoBehaviour { string url = "服务器链接,服务端会提供!"; /// <summary> /// 上传到服务器 /// </summary> public void ToShengGif() { StartCoroutine(UploadVideo()); } // 上传视频 IEnumerator UploadVideo() { byte[] gifByte = File.ReadAllBytes("E:/Work/ffepgtest/gif/a.gif"); WWWForm form = new WWWForm(); //根据自己长传的文件修改格式 form.AddBinaryData("file", gifByte, "myGif.mp4", "a/gif"); using (UnityWebRequest www = UnityWebRequest.Post(url, form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { string text = www.downloadHandler.text; Debug.Log("服务器返回值" + text);//正确打印服务器返回值 } } } }
发送成功后会有提示。
(注:发送Json方式也是一样将地址改变就行.json)
/// <summary> /// 直接上传整个Json文件到服务器,正式使用 /// </summary> /// <returns></returns> IEnumerator NewNewUpLoad() { byte[] jsonByte = File.ReadAllBytes(Application.persistentDataPath + "/" + "OfflineData" + "_" + ARGlobalData.SuccessScanUserID + ".json"); WWWForm form = new WWWForm(); //根据自己长传的文件修改格式 form.AddBinaryData("file", jsonByte, "stepNoPhoto.json", "stepNoPhoto/json"); using (UnityWebRequest www = UnityWebRequest.Post(ARGlobalData.NewConfigurePathStr + "/TPlant-inspect/api/inspect/importData", form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log("服务器上传失败" + www.error); IsOfflineUploadDataSuccess = false; } else { Debug.Log("成功"); //string text = www.downloadHandler.text; IsOfflineUploadDataSuccess = true; //Debug.Log("服务器返回值" + text);//正确打印服务器返回值 } } }
保存Json到本地
public class OfflineGameStatus { public OfflineGameStatus(){}; public int sceneId;//场景id public string staffNumber;//巡检 员工号 public OfflineDevices[] off1ineDevices; public int TotalPoint;// 总时间分数 public int SkipScanGrade;//跳过扫描分数 } [Serializable] public class OfflineDevices public int taskId;//任务id public int actionId;//动作id public int deviceId; public OfflineSteps offl ineSteps; public int SingleDeviceCheckTime;// 单项巡检时间 public OfflinePhotos [] offlinePhotos;//设 备图片信息 [Serializable] public class OfflineSteps { public int stepId; public string opTime;//步 骤巡检时间 public string opResult;//步骤巡检结果 } [Serializable] public class offlinePhotos { public int stepId; public string base64str;//图片信息 }
/// <summary> /// 每个设备检查完成上传一次数据(本地保存) /// </summary> /// <param name="name"></param> public void OnOfflineUploadData(string name) { //2021.10.19改为最后巡检完成,在上传所有数据 if (ARGameManagerLogic.ARGameManagerLogicInstance.nextStepID == -1)//一个设备检查完成 { //StartCoroutine(UpLoadData()); // NewUpLoadData(); if (OfflineDevicesDic != null && OfflineDevicesDic.Count != 0) { //总体信息 offlineGameStatus = new OfflineGameStatus(); offlineGameStatus.sceneId = ARGameJsonDateHandle.ARGameJsonDateHandleInstance.CurrentTasks.sceneId; offlineGameStatus.staffNumber = ARGlobalData.SuccessScanUserID; offlineGameStatus.TotalScore = ARScroingTimeManager.ARScroingTimeManagerInstance.TotalPointTemp; //offlineGameStatus.SkipScanScore = ARGlobalData.SkipScanScore;///2021.10.15注释 ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanGrade = ARScroingModuleManager.ARScroingModuleManagerInstance.OnSkipScanningScroing(); offlineGameStatus.SkipScanScore = ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanGrade; offlineGameStatus.TotalTime = ARScroingTimeManager.ARScroingTimeManagerInstance.TotalScroingTime; offlineGameStatus.SkipScanNumber = ARScroingModuleManager.ARScroingModuleManagerInstance.SkipScanNum; offlineGameStatus.inspectTaskId = ARGlobalData.inspectTaskId; offlineGameStatus.offlineDevices = new OfflineDevices[OfflineDevicesDic.Values.Count]; OfflineDevicesDic.Values.CopyTo(offlineGameStatus.offlineDevices, 0);//将OfflineDevicesDic.Values复制到(offlineGameStatus.offlineDevices数组中,起始位置为0) Debug.Log(offlineGameStatus.inspectTaskId); // OfflineUpLoadJson = JsonMapper.ToJson(offlineGameStatus);//保存本地中文乱码 string LocalJson = JsonUtility.ToJson(offlineGameStatus);//保存本地中文不乱码 string savePath1 = Application.persistentDataPath + "/" + name + "_" + ARGlobalData.SuccessScanUserID + ".json"; ////File.WriteAllText(savePath, LocalJson); strTest.Clear(); strTest.Add(LocalJson); File.WriteAllLines(savePath1, (string[])strTest.ToArray(typeof(string))); } // Debug.Log("请求1"); // StartCoroutine(NewNewUpLoad());//2021.10.19暂时隐藏改为最后巡检完成,在上传所有数据 // AROfflineUploadData.AROfflineUploadDataInstance.OnFormalOfflineUploadData("OfflineData"); } }
//总体信息 offlineGameStatus = new OfflineGameStatus() ; offlineGameStatus. sceneId = 0; offlineGameStatus. TotalPoint = 100 ; offlineGameStatus. SkipScanGrade = 100; offlineGameStatus. offlineDevices = new OfflineDevices [OfflineDevicesDic.Values.Count]; OfflineDevicesDic.Values.CopyTo(offlineGameStatus. offlineDevices, 0) ;//将OfflineDevicesDic.Vaue复制到((offlineGameStatus. offlineDevices数组中,起始位置为0) 0fflineUpLoadJson = JsonMapper. ToJson (offlineGameStatus) ;//保存本地中文乱码 string LocalJson = JsonUtility. ToJson (offlineGameStatus) ;//保存本地中文不乱码 string savePath1 = Application. persi stentDataPath +”/” + name +””+ ARGlobalDat////File. WriteAllText (savePath, LocalJson) ; strTest. Clear() ; strTest. Add (LocalJson) ; File. WriteAllLines (savePath1, (string[]) strTest. ToArray (typeof (string)));//打印保存文件