Unity断点续传下载

4 篇文章 0 订阅

 Unity使用System.Net下载

using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.IO;
public class Downloader : MonoBehaviour
{
    AsyncOperation l;
    private string savePath;
    void Start()
    {
        // Application.backgroundLoadingPriority = ThreadPriority.Low;
        // l =  Application.LoadLevelAsync("game");
        //StartCoroutine(FPointDown(@"http://39.100.50.21:8071/Video/DS/0630.mp4", "d:/qq.rar"));

#if UNITY_EDITOR
        savePath = Application.streamingAssetsPath + "/Download/test.jpg";

#endif

#if UNITY_STANDALONE_WIN
        savePath = Application.dataPath + "/Download/test.jpg";

#endif

        StartCoroutine(FPointDown(@"http://120.131.3.177:8081/download/3", savePath));
    }
    void OnGUI()
    {
        GUILayout.Button(t);
    }

    private void OnDisable()
    {
        
    }
    void OnApplicationQuit()
    {
        print("stop");
        StopCoroutine("FPointDown");
    }
    string t = "";
    IEnumerator downfile(string url, string LocalPath)
    {
        Uri u = new Uri(url);
        HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
        mRequest.Method = "GET";
        mRequest.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();
        Stream sIn = wr.GetResponseStream();
        FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write);
        long length = wr.ContentLength;
        long i = 0;
        decimal j = 0;
        while (i < length)
        {
            byte[] buffer = new byte[1024];
            i += sIn.Read(buffer, 0, buffer.Length);
            fs.Write(buffer, 0, buffer.Length);
            if ((i % 1024) == 0)
            {
                j = Math.Round(Convert.ToDecimal((Convert.ToDouble(i) / Convert.ToDouble(length)) * 100), 4);
                t = "当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + i + "字节 下载进度" + j.ToString() + "%";
            }
            else
            {
                t = "当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + i + "字节";
            }
            yield return false;
        }
        sIn.Close();
        wr.Close();
        fs.Close();
    }
    //断点下载
    IEnumerator FPointDown(string uri, string saveFile)
    {
        //打开网络连接 
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uri);
        System.Net.HttpWebRequest requestGetCount = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uri);
        long countLength = requestGetCount.GetResponse().ContentLength;
        //打开上次下载的文件或新建文件 
        long lStartPos = 0;
        System.IO.FileStream fs;
        if (System.IO.File.Exists(saveFile))
        {
            fs = System.IO.File.OpenWrite(saveFile);
            lStartPos = fs.Length;
            if (countLength - lStartPos <= 0)
            {
                fs.Close();
                t = "已经";
                yield break;
            }
            fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针 
        }
        else
        {
            fs = new System.IO.FileStream(saveFile, System.IO.FileMode.Create);
        }
        if (lStartPos > 0)
        {
            request.AddRange((int)lStartPos); //设置Range值
            print(lStartPos);
        }
        //向服务器请求,获得服务器回应数据流 
        System.IO.Stream ns = request.GetResponse().GetResponseStream();
        int len = 1024 * 8;
        byte[] nbytes = new byte[len];
        int nReadSize = 0;
        nReadSize = ns.Read(nbytes, 0, len);
        while (nReadSize > 0)
        {
            fs.Write(nbytes, 0, nReadSize);
            nReadSize = ns.Read(nbytes, 0, len);
            t = "已下载:" + fs.Length / 1024 + "kb /" + countLength / 1024 + "kb";
            yield return false;
        }
        ns.Close();
        fs.Close();
    }
}

使用UnityEngine.Networking下载

using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class DownloadTest : MonoBehaviour
{
    private bool _isStop;       //是否暂停

    public Slider ProgressBar; //进度条
    public Text SliderValue; //滑动条值
    private Button startBtn;    //开始按钮
    private Button pauseBtn;    //暂停按钮
    //private string Url = "http://39.100.50.21:8071/Video/DS/0630.mp4";
    //private string Url = "http://120.131.3.177:8081/download/2";

    public static string filePath = Application.streamingAssetsPath + "/Download/test.zip";

    /// <summary>
    /// 初始化UI界面及给按钮绑定方法
    /// </summary>
    void Start()
    {

        //初始化进度条和文本框
        ProgressBar.value = 0;
        SliderValue.text = "0.0%";
        startBtn = GameObject.Find("Start Button").GetComponent<Button>();
        startBtn.onClick.AddListener(OnClickStartDownload);
        pauseBtn = GameObject.Find("Pause Button").GetComponent<Button>();
        pauseBtn.onClick.AddListener(OnClickStop);

    }


    /// <summary>
    /// 回调函数:开始下载
    /// </summary>
    public void OnClickStartDownload()
    {
        // 注意真机上要用Application.persistentDataPath
        StartCoroutine(DownloadFile(NetTest.SofeworeURL, filePath, CallBack));
    }


    /// <summary>
    /// 协程:下载文件
    /// </summary>
    /// <param name="url">请求的Web地址</param>
    /// <param name="filePath">文件保存路径</param>
    /// <param name="callBack">下载完成的回调函数</param>
    /// <returns></returns>
    IEnumerator DownloadFile(string url, string filePath, Action callBack)
    {
        UnityWebRequest huwr = UnityWebRequest.Head(url); //Head方法可以获取到文件的全部长度
        yield return huwr.SendWebRequest();
        if (huwr.isNetworkError || huwr.isHttpError) //如果出错
        {
            Debug.Log(huwr.error); //输出 错误信息
        }
        else
        {
            long totalLength = long.Parse(huwr.GetResponseHeader("Content-Length")); //首先拿到文件的全部长度
            string dirPath = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dirPath)) //判断路径是否存在
            {
                Directory.CreateDirectory(dirPath);
            }

            //创建一个文件流,指定路径为filePath,模式为打开或创建,访问为写入
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                long nowFileLength = fs.Length; //当前文件长度
                Debug.Log("已下载文件长度:"+fs.Length);
                if (nowFileLength < totalLength)
                {
                    Debug.Log("未下载完成");
                    fs.Seek(nowFileLength, SeekOrigin.Begin);       //从头开始索引,长度为当前文件长度
                    UnityWebRequest uwr = UnityWebRequest.Get(url); //创建UnityWebRequest对象,将Url传入
                    uwr.SetRequestHeader("Range", "bytes=" + nowFileLength + "-" + totalLength);
                    uwr.SendWebRequest();                      //开始请求
                    if (uwr.isNetworkError || uwr.isHttpError) //如果出错
                    {
                        Debug.Log(uwr.error); //输出 错误信息
                    }
                    else
                    {
                        long index = 0;     //从该索引处继续下载
                        while (!uwr.isDone) //只要下载没有完成,一直执行此循环
                        {
                            if (_isStop) break;
                            yield return null;
                            byte[] data = uwr.downloadHandler.data;
                            if (data != null)
                            {
                                long length = data.Length - index;
                                fs.Write(data, (int)index, (int)length); //写入文件
                                index += length;
                                nowFileLength += length;
                                ProgressBar.value = uwr.downloadProgress;
                                SliderValue.text = Mathf.Floor(uwr.downloadProgress * 100) + "%"; 

                                if (uwr.isDone) //如果下载完成了
                                {
                                    Debug.Log("isDone >= totalLength");
                                    ProgressBar.value = 1; //改变Slider的值
                                    SliderValue.text = 100 + "%";
                                    callBack?.Invoke();
                                }
                            }
                        }
                    }
                }
                else
                {
                    ProgressBar.value = 1; //改变Slider的值
                    SliderValue.text = 100 + "%";
                    callBack?.Invoke();
                }



            }
        }
    }

    /// <summary>
    /// 下载完成后的回调函数
    /// </summary>
    void CallBack()
    {
        Debug.Log("下载完成");
    }

    /// <summary>
    /// 暂停下载
    /// </summary>
    public void OnClickStop()
    {
        if (_isStop)
        {
            pauseBtn.GetComponentInChildren<Text>().text = "暂停下载";
            Debug.Log("继续下载");
            _isStop = !_isStop;
            OnClickStartDownload();

        }
        else
        {
            pauseBtn.GetComponentInChildren<Text>().text = "继续下载";
            Debug.Log("暂停下载");
            _isStop = !_isStop;
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值