当前位置: 首页 > news >正文

Unity UnityWebRequest 向php后端上传图片文件

之前测试功能写过一次,因为代码忘记保存,导致真正用到的时候怎么也想不起来当初怎么写的了,复现后还是写个文章记录一下,省的下次再忘记。

php后端

/*** 图片保存到本地*/
public function uploadLocalImage()
{try {$img = $this->_request->file('img');if (empty($img)) {throw new \Exception('缺少图片参数');}$writeDir = "images/".date('Ymd');$dir = "D:/phpstudy_pro/WWW/vkm_locarun_dist/dist/".$writeDir;//$dir = "local_run/" . date('Ymd'); //linux调试地址if (!file_exists($dir)) {mkdir($dir, 0777, true);}$extension = substr($img->getMimeType(), -3);if ($extension == 'bmp') {$fileName = UtilService::createOrderNo() . '.bmp';}if ($extension == 'png') {$fileName = UtilService::createOrderNo() . '.png';}else{$fileName = UtilService::createOrderNo() . '.jpg';}$imgContent = file_get_contents($img);file_put_contents($dir . '/' . $fileName, $imgContent);$localhostImg = env('CLIENT_URL') . $writeDir . '/' . $fileName;//http://127.0.0.1:8000/xxx/20231016/xxx.jpg 读取方式$this->returnSuccess($localhostImg);} catch (\Exception $e) {$this->returnFault($e->getMessage());}
}

Unity C#

/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="filePaths">文件路径</param>
void UploadToLocalServer(string[] filePaths)
{int count = filePaths.Length;urls = new string[count];isUploaded = new bool[count];string filePath;//文件命为上传OSS时的keyfor (int i = 0; i < count; i++){int current = i;filePath = filePaths[current];if (File.Exists(filePath)){File.SetAttributes(filePath, FileAttributes.Normal);StartCoroutine(UploadToLocal(filePath, current));}else{urls[current] = "none";}}
}
IEnumerator UploadToLocal(string filePath, int index)
{byte[] fileByte = File.ReadAllBytes(filePath);WWWForm form = new WWWForm();//根据自己上传的文件修改格式,img是接口请求json参数的key, //最后一个参数是图片的mimeType, 因为上传的图片有jpg、png、bmp几种格式,此处取文件后缀和image组合字符串作为mimeTypeform.AddBinaryData("img", fileByte, Path.GetFileName(filePath), $"image/{Path.GetExtension(filePath)}");Helper.Log($"{Config.SystemConfig.sendHost}/uploadLocalImage");using (UnityWebRequest www = UnityWebRequest.Post($"{Config.SystemConfig.sendHost}/uploadLocalImage", form)){yield return www.SendWebRequest();if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError){urls[index] = "error";Helper.LogError($"[ERROR] {filePath}, msg: {www.error}");}else{string text = www.downloadHandler.text;//Helper.Log("服务器返回值" + text);JObject json = JObject.Parse(text);if (json["msg"].ToString().Equals("success")){urls[index] = json["data"].ToString();Helper.Log($"[SUCCESS] {urls[index]}");}else{urls[index] = "error";Helper.LogError($"[ERROR] {filePath}, msg: {text}");}isUploaded[index] = true;}}
}

搞定。

http://www.lryc.cn/news/287901.html

相关文章:

  • Vscode 顶部Menu(菜单)栏消失如何恢复
  • Jenkins相关
  • 禅道的安装以及使用
  • 马尔可夫预测(Python)
  • 双向队列的创建队首与队尾的操作deque()
  • 一、MongoDB、express的安装和基本使用
  • 被困住了——如何从层级结构中获取子集
  • leetcode1237. 找出给定方程的正整数解
  • sqlmap使用教程(6)-注入技术拓展
  • 苹果Find My市场需求火爆,伦茨科技ST17H6x芯片助力客户量产
  • 3DMAX初级小白班第一课:菜单栏介绍
  • Windows中Zookeeper与kafka的安装配置
  • QT 官方例程阅读: XML Patterns 相关
  • 基于SpringBoot IP黑白名单的实现
  • Redis客户端之Redisson(二)Redisson分布式锁
  • 掌握大语言模型技术: 推理优化
  • git如何导出提交记录及修改的文件清单?
  • 从零开始:Ubuntu Server中MySQL 8.0的安装与Django数据库配置详解
  • Vue基础知识
  • 瀑布流布局 (初版)
  • 硕士毕业论文写作笔记
  • 成本更低、更可控,云原生可观测新计费模式正式上线
  • 5.列表选择弹窗(BottomListPopup)
  • (十三)Head first design patterns原型模式(c++)
  • Python基础之数据库操作
  • redis-发布缓存
  • Stata17安装教程
  • Java PDFBox 提取页数、PDF转图片
  • 【代码随想录14】104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数
  • AWS 专题学习 P10 (Databases、 Data Analytics)