【发布时间】:2019-11-26 11:55:47
【问题描述】:
我有以下使用 Unity 的 UnityWebRequest API (Unity 2019.2.13f1) 上传代码:
public IEnumerator UploadJobFile(string jobId, string path)
{
if (!File.Exists(path))
{
Debug.LogError("The given file to upload does not exist. Please re-create the recording and try again.");
yield break;
}
UnityWebRequest upload = new UnityWebRequest(hostURL + "/jobs/upload/" + jobId);
upload.uploadHandler = new UploadHandlerFile(path);
upload.downloadHandler = new DownloadHandlerBuffer();
upload.method = UnityWebRequest.kHttpVerbPOST;
upload.SetRequestHeader("filename", Path.GetFileName(path));
UnityWebRequestAsyncOperation op = upload.SendWebRequest();
while (!upload.isDone)
{
//Debug.Log("Uploading file...");
Debug.Log("Uploading file. Progress " + (int)(upload.uploadProgress * 100f) + "%"); // <-----------------
yield return null;
}
if (upload.isNetworkError || upload.isHttpError)
{
Debug.LogError("Upload error:\n" + upload.error);
}
else
{
Debug.Log("Upload success");
}
// this is needed to clear resources on the file
upload.Dispose();
}
string hostURL = "http://localhost:8080";
string jobId = "manualUploadTest";
string path = "E:/Videos/short.mp4";
void Update()
{
if (Input.GetKeyDown(KeyCode.O))
{
Debug.Log("O key was pressed.");
StartCoroutine(UploadAndTest(jobId, path));
}
}
我在服务器端收到的文件损坏了,尤其是当它们更大(30 MB 或更大)时。它们最后缺少字节,有时整个字节块在中间重复。
- 在同一台机器上测试客户端和服务器或在不同机器上运行时都会发生这种情况。
- 服务器没有抱怨 - 从它的角度来看,没有发生传输错误。
我注意到,如果我注释掉对upload.uploadProgress 的访问(例如,改用它上面的注释掉的调试行,它只打印一个字符串文字),文件保持不变。完全放弃 wile 循环并将其替换为 yield return op 也可以。
我在外部循环中反复测试了这种奇怪的行为 - 通常在使用“错误”代码重复最多 8 次后,文件似乎已损坏。如果我使用“正确”变体,则连续 100 次上传(更新:500 次)成功。
upload.uploadProgress 有副作用吗? 无论如何,如果我打印 op.progress 会发生同样的情况 - 文件也会损坏。
【问题讨论】: