Files
plugin-library/Assets/Main/Script/Runtime/Tools/ZipTool.cs
2025-05-23 18:26:47 +08:00

116 lines
4.3 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace Stary.Evo
{
public class ZipTool
{
// 新增:带进度回调的下载解压方法
public static async UniTask<string[]> DownloadAndUnzipAsync(string url, string extractPath,
Action<float> downloadProgress = null, Action<float> unzipProgress = null)
{
string tempPath = Path.Combine(Application.persistentDataPath, "temp.zip");
try
{
// 下载ZIP文件
using( UnityWebRequest request =WebRequester(url))
{
request.downloadHandler = new DownloadHandlerFile(tempPath);
var operation = request.SendWebRequest();
while (!operation.isDone)
{
downloadProgress?.Invoke(request.downloadProgress);
await UniTask.Yield();
}
if (request.result != UnityWebRequest.Result.Success)
{
throw new Exception($"下载失败:{request.error}");
}
}
// 解压下载的文件
return await UnzipAsync(tempPath, extractPath, unzipProgress);
}
finally
{
// 清理临时文件
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
}
}
// 修改:添加进度回调参数
public static async UniTask<string[]> UnzipAsync(string zipPath, string extractPath,
Action<float> progressCallback = null)
{
try
{
List<string> pathList = new List<string>();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
float totalEntries = archive.Entries.Count;
float processed = 0;
foreach (ZipArchiveEntry entry in archive.Entries)
{
string filePath = Path.Combine(extractPath, entry.FullName);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
if (!string.IsNullOrEmpty(entry.Name))
{
using (Stream inputStream = entry.Open())
using (FileStream outputStream = File.Create(filePath))
{
await inputStream.CopyToAsync(outputStream);
pathList.Add(outputStream.Name);
}
}
processed++;
float progress = processed / totalEntries;
progressCallback?.Invoke(progress);
Debug.Log($"解压进度: {progress:P0}");
}
}
Debug.Log($"解压完成: {extractPath}");
return pathList.ToArray();
}
catch (Exception ex)
{
Debug.LogError($"解压失败: {ex.Message}");
throw;
}
}
/// <summary>
/// 自定义网络请求器需要登录
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static UnityWebRequest WebRequester(string url)
{
var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
var authorization = GetAuthorization(AppConfig.USERNAME, AppConfig.PASSWORD);
request.SetRequestHeader("AUTHORIZATION", authorization);
return request;
}
private static string GetAuthorization(string userName, string password)
{
string auth = userName + ":" + password;
var bytes = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth);
return "Basic " + System.Convert.ToBase64String(bytes);
}
}
}