赞
踩
这里可以看到 需要我们发的是一个file文件 参数是你想要上传的图片
拿到服务器的IP
用WWWForm发送数据
接收到服务器消息后 用 LitJson 来解析
- using System.Collections;
- using UnityEngine;
- using UnityEngine.UI;
- using System.IO;
- using UnityEngine.Networking;
- using LitJson;
-
- public class BtnTest : MonoBehaviour
- {
- public static BtnTest instance;
-
- //config里拿到的数据
- public string[] Config;
-
- public Button btn;
-
-
- public string serverURL; // 服务器URL
- public string videoFieldName; // 视频字段名
- public string videoFilePath; // 视频文件路径
-
- public MsgClass pngStr; //图片链接类
-
- private void Awake()
- {
- instance = this;
-
- Config = File.ReadAllLines(Application.streamingAssetsPath + "/Config.txt");
- serverURL = Config[0].Split('=')[1];
- }
- // Start is called before the first frame update
- void Start()
- {
- videoFieldName = "file";
- videoFilePath = Application.streamingAssetsPath + "/123.png";
-
- btn.onClick.AddListener(() =>
- {
- StartCoroutine(SendVideo());
- Debug.Log("向服务器发送图片");
- });
- }
- /// <summary>
- /// 根据本地视频地址向服务器传录好的视频
- /// </summary>
- /// <returns></returns>
- public IEnumerator SendVideo()
- {
- // 创建一个新的表单
- WWWForm form = new WWWForm();
-
- // 添加视频数据到表单中
- byte[] videoData = System.IO.File.ReadAllBytes(videoFilePath);
- //form.AddField("openid", "123");
- //form.AddField("code", "1002");
- form.AddBinaryData(videoFieldName, videoData);
-
- // 发送POST请求到服务器
- UnityWebRequest request = UnityWebRequest.Post(serverURL, form);
- yield return request.SendWebRequest();
-
- if (request.isNetworkError || request.isHttpError)
- {
- Debug.LogError("上传照片成功: " + request.error);
- }
- else
- {
- Debug.Log("照片上传成功!");
- Debug.Log("服务器响应: " + request.downloadHandler.text);
- pngStr= JsonMapper.ToObject<MsgClass>(request.downloadHandler.text);
- Debug.Log("图片网络链接:"+pngStr.fileName);
- }
- }
-
- /// <summary>
- /// 服务器消息模板
- /// </summary>
- public class MsgClass
- {
- /// <summary>
- /// 暂无互动
- /// </summary>
- public string msg { get; set; }
- /// <summary>
- ///
- /// </summary>
- public string fileName { get; set; }
- /// <summary>
- ///
- /// </summary>
- public int state { get; set; }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。