为测试在本地搭建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;
}
}
代码为测试功能使用,在项目使用时需要进行完善。