如何使用UnityWebRequest.Post()将多个文件上载到服务器;

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (1113)

我正在尝试使用UnityWebRequest.Post()上传多个文件,这是我的代码。

 public void UploadFiles()
 {
     string[] path = new string[3];
     path[0] = "D:/File1.txt";
     path[1] = "D:/File2.txt";
     path[2] = "D:/File3.txt";

     UnityWebRequest[] files = new UnityWebRequest[3];
     WWWForm form = new WWWForm();

     for (int i = 0; i < files.Length; i++)
     {
         files[i] = UnityWebRequest.Get(path[i]);
         form.AddBinaryData("files[]", files[i].downloadHandler.data, Path.GetFileName(path[i]));
     }

     UnityWebRequest req = UnityWebRequest.Post("http://localhost/File%20Upload/Uploader.php", form);
     yield return req.SendWebRequest();

     if (req.isHttpError || req.isNetworkError)
         Debug.Log(req.error);
     else
         Debug.Log("Uploaded " + files.Length + " files Successfully");
 }

但是,文件在目标位置创建,大小为0字节。

这是我的Uploader.php代码

 <$php
   $total = count($_FILES['files']['name']);
   $uploadError = false;
   for ( $i = 0; $i < $total; $i++)
   {
     $tmpFilePath = $_FILES['files']['tmp_name'][$i];

     if ($tmpFilePath != "")
     {
         $newFilePath = "Uploads/".$_FILES['files']['name'][$i];
         if (!move_uploaded_file($tmpFilePath, $newFilePath))
             $uploadError = true;
     }
   }
   if ($uploadError)
       echo "Upload Error";
   else
       echo "Uploaded Successfully";
 ?>

我使用此HTML示例作为参考。在浏览器中,HTML代码完美无缺。Unity中存在问题。

 <form enctype="multipart/form-data" action="Uploader.php" method="POST">
     Choose a file to Upload:
     <input type="file" name="files[]" multiple="multiple" /><br>
     <input type="submit" value="Upload File" />
 </form>
提问于
用户回答回答于

for loopC#代码中,在请求文件之后,我们必须在获取文件时屈服。因此yield return files[i].SendWebRequest();在请求文件后使用将解决问题。这是修改后的代码:

IEnumerator UploadMultipleFiles()
{
    string[] path = new string[3];
    path[0] = "D:/File1.txt";
    path[1] = "D:/File2.txt";
    path[2] = "D:/File3.txt";

    UnityWebRequest[] files = new UnityWebRequest[path.Length];
    WWWForm form = new WWWForm();

    for (int i = 0; i < files.Length; i++)
    {
        files[i] = UnityWebRequest.Get(path[i]);
        yield return files[i].SendWebRequest();
        form.AddBinaryData("files[]", files[i].downloadHandler.data, Path.GetFileName(path[i]));
    }

    UnityWebRequest req = UnityWebRequest.Post("http://localhost/File%20Upload/Uploader.php", form);
    yield return req.SendWebRequest();

    if (req.isHttpError || req.isNetworkError)
        Debug.Log(req.error);
    else
        Debug.Log("Uploaded " + files.Length + " files Successfully");
}

其余的代码很好。PHP代码没有变化。HTML代码仅供参考。

扫码关注云+社区

领取腾讯云代金券