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时的key
    for (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组合字符串作为mimeType
    form.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;
        }
    }
}

搞定。

相关推荐

  1. Unity UnityWebRequest php图片文件

    2024-01-23 14:10:01       33 阅读
  2. 文件使用阿里云oss存储文件图片

    2024-01-23 14:10:01       14 阅读
  3. 【Web】实现文件

    2024-01-23 14:10:01       8 阅读
  4. uniapp 多张图片到django

    2024-01-23 14:10:01       34 阅读
  5. el-upload图片给SpringBoot

    2024-01-23 14:10:01       13 阅读
  6. php 如何判断是否文件图片

    2024-01-23 14:10:01       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-23 14:10:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-23 14:10:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-23 14:10:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-23 14:10:01       18 阅读

热门阅读

  1. C Primer Plus(第六版)13.11 编程练习 第9题

    2024-01-23 14:10:01       33 阅读
  2. Rust 中的 Option、Result 和 ? 运算符

    2024-01-23 14:10:01       33 阅读
  3. Rust 并发

    2024-01-23 14:10:01       29 阅读
  4. 树莓派ubuntu:CSI接口摄像头安装驱动程序及测试

    2024-01-23 14:10:01       34 阅读
  5. UNITY BUILD加速cmake 编译

    2024-01-23 14:10:01       33 阅读
  6. VSCode 中 Tab 键突然不能缩进了

    2024-01-23 14:10:01       32 阅读
  7. 边缘计算的挑战和机遇

    2024-01-23 14:10:01       43 阅读
  8. R语言【cli】——ansi_strtrim():截断ANSI字符串

    2024-01-23 14:10:01       30 阅读
  9. NLP深入学习(七):词向量

    2024-01-23 14:10:01       32 阅读
  10. promise

    2024-01-23 14:10:01       35 阅读