Unity 使用UnityWebRequest从服务器中下载文件

为测试在本地搭建IIS服务器(本地搭建IIS服务器方法),将需要下载的文件拷贝到指定位置,通过url即可下载文件到指定的文件夹目录中。测试代码如下

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

public class DownloadingTest : MonoBehaviour {


    UnityWebRequest webRequest;
    private string downloadUrl = "";
    private string savePath = "";//如"E://"
    private string downloadFileName = "";
    
    // Use this for initialization
    void Start () {
        downloadUrl = "http://192.168.31.168:8181/git.jpg";//下载链接
        savePath = Application.dataPath+"/";
        downloadFileName = "git.jpg";


        StartCoroutine(Down(downloadUrl));
	}
	
	// Update is called once per frame
	void Update () {
       // Debug.Log("下载进度:"+GetProcess());
	}
    /// <summary>
    /// 根据URL下载文件
    /// </summary>
    /// <param name="downloadingUrl"></param>
    /// <returns></returns>
    IEnumerator Down(string downloadingUrl)

    {
        //发送请求
        webRequest = UnityWebRequest.Get(downloadingUrl);
        webRequest.timeout = 30;//设置超时,若webRequest.SendWebRequest()连接超时会返回,且isNetworkError为true
        yield return webRequest.SendWebRequest();

        if (webRequest.isNetworkError)
        {
            Debug.Log("Download Error:" + webRequest.error);
        }
        else {
            //获取二进制数据

            var File = webRequest.downloadHandler.data;

            //创建文件写入对象

            FileStream nFile = new FileStream(savePath + downloadFileName, FileMode.Create);

            //写入数据

            nFile.Write(File, 0, File.Length);

            nFile.Close();
        }

      

    }

    /// <summary>
    /// 获取下载进度
    /// </summary>
    /// <returns></returns>
    public float GetProcess() {
        if (webRequest!=null) {
            return webRequest.downloadProgress;
        }
        return 0;
    }
    /// <summary>
    /// 获取当前下载内容长度
    /// </summary>
    /// <returns></returns>
    public long GetCurrentLength() {
        if (webRequest != null)
        {
            return (long)webRequest.downloadedBytes;
        }
        return 0;
    }
}

代码为测试功能使用,在项目使用时需要进行完善。

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值