【问题标题】:Get file/AssetBundle size from http request before downloading file在下载文件之前从 http 请求中获取文件/AssetBundle 大小
【发布时间】:2018-08-03 02:09:27
【问题描述】:

问题:

我想在完成下载文件之前获取assetBundle 的大小。我可以向用户显示剩余时间。在 Unity2018.2 中,我们可以得到 文件大小 或 下载的文件大小 让我乘以 progress 吗?或者还有其他方法可以计算剩余时间?

我知道 WWW.responseHeaders 包含信息,但似乎需要完成下载。

这是我目前的代码。

    using (WWW downloadPackageWWW = new WWW(pkg.url))
    {
        while (!downloadPackageWWW.isDone)
        {
            print("progress: " + downloadPackageWWW.progress * 100 + "%");    
            yield return null;
        }

        if (downloadPackageWWW.error != null)
            print("WWW download had an error:" + downloadPackageWWW.error);
        if (downloadPackageWWW.responseHeaders.Count > 0) 
            print(pkg.fileName + ": " + downloadPackageWWW.responseHeaders["Content-Length"]+" byte");

        byte[] bytes = downloadPackageWWW.bytes;
        File.WriteAllBytes(pkgPath, bytes);

    }

--

更新:

为了得到剩余时间,我提出了一个理想的计算方法,即Time.deltaTime,我们不需要知道总文件大小和下载速度。

float lastProgress = 0;
while (!www.isDone)
{  
     float deltaProgress = www.progress - lastProgress;
     float progressPerSec = deltaProgress / Time.deltaTime;
     float remaingTime = (1 - www.progress) / progressPerSec;
     print("Remaining: " + remaingTime + " sec"); 
     lastProgress = www.progress;
     yield return null;
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您应该使用 Unity 的 UnityWebRequest API 来发出我们的请求。在您当前的 Unity 版本中,WWW API 现在在 UnityWebRequest 的底层实现,但它仍然缺少许多功能。

    您可以通过两种方式在不下载或等待文件完成下载的情况下获取文件的大小:

    1. 使用UnityWebRequest.Head 发出HEAD 请求。然后您可以使用UnityWebRequest.GetResponseHeader("Content-Length") 来获取数据的大小。

    IEnumerator GetFileSize(string url, Action<long> resut)
    {
        UnityWebRequest uwr = UnityWebRequest.Head(url);
        yield return uwr.SendWebRequest();
        string size = uwr.GetResponseHeader("Content-Length");
    
        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log("Error While Getting Length: " + uwr.error);
            if (resut != null)
                resut(-1);
        }
        else
        {
            if (resut != null)
                resut(Convert.ToInt64(size));
        }
    }
    

    用法:

    void Start()
    {
        string url = "http://ipv4.download.thinkbroadband.com/5MB.zip";
        StartCoroutine(GetFileSize(url,
        (size) =>
        {
            Debug.Log("File Size: " + size);
        }));
    }
    

    2。另一种选择是将UnityWebRequest 与DownloadHandlerScript 一起使用,然后覆盖void ReceiveContentLength(int contentLength) 函数。调用 SendWebRequest 函数后,ReceiveContentLength 函数应该在 contentLength 参数中为您提供下载大小。然后,您应该中止 UnityWebRequest 请求。 Here 是一个关于如何使用 DownloadHandlerScript 的示例。

    我会选择第一个解决方案,因为它更简单、更容易并且需要更少的资源来工作。

    【讨论】:

    • 感谢您的回复。我会尝试这些解决方案。
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2013-06-29
    • 2012-08-18
    相关资源
    最近更新 更多