unity使用线程下载文件,支持断点续传
2019-12-31 本文已影响0人
Walk_In_Jar
image.png
用一个简单的滑动条来显示下载进度
支持断点续传
滑动条部分代码
using UnityEngine;
using UnityEngine.UI;
public class LodingManager : MonoBehaviour
{
public Transform[] its;
public float speed;
public Transform sli;
public Text text;
private float processing;
HTTPDownLoad downLoad;
private void Start()
{
string s = "https://qd.myapp.com/myapp/qqteam/pcqq/PCQQ2019.exe";
DownLoadFile(s);
}
public void DownLoadFile(string url)//下载指定文件
{
processing = 0;
downLoad = new HTTPDownLoad(url, Application.dataPath + "/DownLoad/", 5000);
}
void Update()
{
foreach (Transform item in its)
{
item.localPosition += new Vector3(Time.deltaTime, 0) * speed;
if (item.localPosition.x > 700)
{
item.localPosition -= new Vector3(92.376f * 16, 0);
}
}
if (downLoad.Status == 0)//更新进度条
{
Pro = downLoad.Progress;
}
if (Input.GetKeyDown(KeyCode.Space))//按空格键下载其他文件
{
string s = "https://dldir1.qq.com/music/clntupate/QQMusic_YQQWinPCDL.exe";
DownLoadFile(s);
}
if (Input.GetKeyDown(KeyCode.Escape))//按返回键暂停下载
{
downLoad.Close();
}
}
public float Pro
{
get
{
return processing;
}
set
{
if (value < 1)
{
while (processing < value)//为什么这么处理呢,让滑动条更平顺的移动
{
processing += 0.01f;
text.text = (int)(100 * processing) + "%";
if (processing <= 1)
sli.localPosition = new Vector3(-1152 + 1152 * processing, 0);
}
}
else if (value == 1)
{
text.text = "100%";
sli.localPosition = new Vector3(0, 0);
}
}
}
}
下载的代码
using System;
using System.Net;
using System.IO;
using System.Threading;
using UnityEngine;
/// <summary>
/// 文件下载
/// </summary>
public class HTTPDownLoad
{
private string postfix = ".temp";//临时文件后缀名
// 下载进度
public float Progress
{
get;
private set;
}
// 状态 0 正在下载 1 下载完成 -1 下载出错
public int Status
{
get;
private set;
}
// 错误信息
public string Error
{
get;
set;
}
// 总长度
public long TotalLength
{
get;
private set;
}
// 保存路径
private string savePath;
// url地址
private string url;
// 超时时间
private int timeout;
// 子线程
private Thread thread;
// 子线程是否停止标志
public bool isStop;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="url">url地址</param>
/// <param name="timeout">超时时间</param>
/// <param name="callback">回调函数</param>
public HTTPDownLoad(string _url, string _savePath, int _timeout)
{
savePath = _savePath;
url = _url;
timeout = _timeout;
DownLoad();
}
/// <summary>
/// 开启下载
/// </summary>
void DownLoad()
{
Status = 0;
isStop = false;
// 开启线程下载
thread = new Thread(StartDownLoad);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 开始下载
/// </summary>
private void StartDownLoad()
{
try
{
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string fileName = url.Split('/')[url.Split('/').Length - 1];
string pathName = savePath + "/" + ErasePostfix(fileName) + postfix;
// 构建文件流
FileStream fs = new FileStream(pathName, FileMode.OpenOrCreate, FileAccess.Write);
// 文件当前长度
long fileLength = fs.Length;
// 文件总长度
TotalLength = GetDownLoadFileSize();
// Debug.LogFormat("fileLen:{0}", TotalLength);
if (fileLength < TotalLength)
{
// 没有下载完成
fs.Seek(fileLength, SeekOrigin.Begin);
// 发送请求开始下载
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.AddRange((int)fileLength);
request.Timeout = timeout;
// 读取文件内容
Stream stream = request.GetResponse().GetResponseStream();
if (stream.CanTimeout)
{
stream.ReadTimeout = timeout;
}
byte[] buff = new byte[4096];
int len = -1;
while ((len = stream.Read(buff, 0, buff.Length)) > 0)
{
if (isStop)
{
break;
}
fs.Write(buff, 0, len);
fileLength += len;
Progress = fileLength * 1.0f / TotalLength;
}
stream.Close();
stream.Dispose();
}
else
{
Progress = 1;
}
fs.Close();
fs.Dispose();
// 标记下载完成
if (Progress == 1)
{
Status = 1;
string filepathName = savePath + "/" + fileName;
if (File.Exists(filepathName))//删除原来的
File.Delete(filepathName);
File.Move(pathName, filepathName);
Debug.Log("下载" + filepathName + "完毕");
}
}
catch (Exception e)
{
Error = e.Message;
Status = -1;
Debug.Log(Error);
}
}
/// <summary>
/// 获取下载的文件大小
/// </summary>
/// <returns>文件大小</returns>
public long GetDownLoadFileSize()
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
request.Timeout = timeout;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return response.ContentLength;
}
/// <summary>
/// 停止下载
/// </summary>
public void Close()
{
isStop = true;
}
private string ErasePostfix(string filePath)
{
return filePath.Substring(0, filePath.LastIndexOf('.'));
}
}
参考修改了其他人的代码,