/// <summary>
/// Untiy下载服务器的某个文件资源
/// </summary>
/// <param name="url">文件的服务器地址</param>
/// <param name="localPath">文件需要保存的本地地址</param>
/// <returns></returns>
public static IEnumerator DownLoadFileFormURL(string url, string localPath)
{
Debug.Log("下载地址:" + url + ",保存路径:" + localPath);
UnityWebRequest headRequest = UnityWebRequest.Head(url);
yield return headRequest.SendWebRequest();
if (!string.IsNullOrEmpty(headRequest.error))
{
Debug.LogError("获取下载的文件大小失败:" + headRequest.error);
yield break;
}
ulong totalLength = ulong.Parse(headRequest.GetResponseHeader("Content-Length"));//获取文件总大小
Debug.Log("获取大小" + totalLength);
headRequest.Dispose();
// 以下是获取文件名的代码逻辑
string fileName = Path.GetFileName(url);
Debug.Log("文件名: " + fileName);
UnityWebRequest Request = UnityWebRequest.Get(url);
//localPath += totalFileName;
localPath = Path.Combine(localPath, fileName);
Request.downloadHandler = new DownloadHandlerFile(Path.Combine(localPath));//append设置为true文件写入方式为接续写入,不覆盖原文件。
FileInfo file = new FileInfo(localPath);
ulong fileLength = (ulong)file.Length;
Debug.Log("文件总共大小:" + fileLength + ",totalLength=" + totalLength);
//设置文件从什么位置开始下载和写入
Request.SetRequestHeader("Range", "bytes=" + fileLength + "-");
if (fileLength < totalLength)
{
Request.SendWebRequest();
while (!Request.isDone)
{
double p = (Request.downloadedBytes + fileLength) / (double)totalLength;
//进度条.value = (float)progress;
Debug.Log("下载进度:" + (p * 100).ToString("F2") + "%");
yield return null;
}
}
if (string.IsNullOrEmpty(Request.error))
{
Debug.Log("下载成功:" + localPath);
}
else
{
Debug.LogError("下载失败:" + Request.error);
}
Request.Dispose();
}