unity3d 通过 http网络下载资源到本地

欢迎加入U3D交流群,群号码:308093702~~~~


string urlPath = "http://.....";//资源网络路径(自己写)

    
    string localPath = @"Assets\....";


    public Text text;


    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartCoroutine(DownLoadFile(urlPath));
        }
        text.text = currentNumShow.ToString();
    }


    /// <summary>


    /// 下载文件


    /// </summary>


    IEnumerator DownLoadFile(string url)


    {


        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);


        request.Method = "GET";


        HttpWebResponse HWR = (HttpWebResponse)request.GetResponse();


        Stream stream = HWR.GetResponseStream();


        FileStream fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write);


        long length = HWR.ContentLength;


        long currentNum = 0;


        decimal currentProgress = 0;






        while (currentNum < length)


        {


            byte[] buffer = new byte[1024];


            currentNum += stream.Read(buffer, 0, buffer.Length);


            fileStream.Write(buffer, 0, buffer.Length);


            if (currentNum % 1024 == 0)


            {


                currentProgress = Math.Round(Convert.ToDecimal(Convert.ToDouble(currentNum) / Convert.ToDouble(length) * 100), 4);


                Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + currentNum + "字节 下载进度" + currentProgress.ToString() + "%");


            }


            else


            {


                Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + currentNum + "字节" + "字节 下载进度" + 100 + "%");


            }


            currentNumShow = currentProgress;


            yield return false;


        }


        HWR.Close();


        stream.Close();


        fileStream.Close();


    }


    decimal currentNumShow;

猜你喜欢

转载自blog.csdn.net/Mr_chenxiansheng/article/details/80239955