unity2021下载文件,支持断点续传,支持MD5,支持进度条显示
时间: 2023-08-18 20:09:16 浏览: 177
Unity 2021中可以使用UnityWebRequest来下载文件并实现断点续传和MD5校验。以下是一个简单的示例代码:
```csharp
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using System;
public class DownloadManager : MonoBehaviour
{
private UnityWebRequest request;
private string downloadUrl;
private string savePath;
private string md5Hash;
private bool isDownloading = false;
public void StartDownload(string url, string path, string md5)
{
downloadUrl = url;
savePath = path;
md5Hash = md5;
if (File.Exists(savePath))
{
// 如果文件已存在,则计算文件的md5值,与给定的md5值进行比较
string fileMd5 = GetMD5HashFromFile(savePath);
if (fileMd5.Equals(md5Hash))
{
// 文件已下载完毕,直接返回
Debug.Log("File already downloaded.");
return;
}
else
{
// 文件未下载完毕,删除已下载的部分,重新下载
File.Delete(savePath);
}
}
isDownloading = true;
request = UnityWebRequest.Get(downloadUrl);
long fileLength = GetDownloadFileSize(downloadUrl);
request.SetRequestHeader("Range", "bytes=" + FileSize(savePath) + "-");
request.downloadHandler = new DownloadHandlerFile(savePath);
StartCoroutine(DownloadFile(fileLength));
}
private IEnumerator DownloadFile(long fileLength)
{
request.SendWebRequest();
while (!request.isDone)
{
float progress = (float)request.downloadedBytes / fileLength;
Debug.Log("Download progress: " + progress);
yield return null;
}
isDownloading = false;
if (!request.isNetworkError && !request.isHttpError)
{
// 下载完成后,计算文件的md5值,与给定的md5值进行比较
string fileMd5 = GetMD5HashFromFile(savePath);
if (fileMd5.Equals(md5Hash))
{
Debug.Log("File downloaded successfully.");
}
else
{
Debug.LogError("MD5 check failed.");
File.Delete(savePath);
}
}
else
{
Debug.LogError("Download failed: " + request.error);
File.Delete(savePath);
}
}
private long GetDownloadFileSize(string url)
{
request = UnityWebRequest.Head(url);
request.SendWebRequest();
while (!request.isDone) { }
if (!request.isNetworkError && !request.isHttpError)
{
return long.Parse(request.GetResponseHeader("Content-Length"));
}
else
{
Debug.LogError("Get file size failed: " + request.error);
return -1;
}
}
private long FileSize(string path)
{
if (File.Exists(path))
{
FileInfo fileInfo = new FileInfo(path);
return fileInfo.Length;
}
else
{
return 0;
}
}
private string GetMD5HashFromFile(string path)
{
if (File.Exists(path))
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
using (var stream = File.OpenRead(path))
{
byte[] hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
else
{
return "";
}
}
}
```
您可以在调用StartDownload方法时,传入下载文件的url、保存路径以及md5值。如果文件已经存在并且md5值与给定的md5值相同,则不会重新下载;否则会删除已下载的部分,重新下载。在下载过程中,可以通过协程获取下载进度并显示进度条。下载完成后,会计算文件的md5值并与给定的md5值进行比较,确保文件的完整性。
阅读全文