我使用文件流来完成您想要实现的操作。这样做的好处是很容易实现暂停功能,实现进度表并在数据流入时运行其他计算。
我希望我可以对下面的所有代码负责,但是其中一些是此处代码的修改版本:http://answers.unity3d.com/questions/300841/ios-download-files-and-store-to-local-drive.html
包括:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
连接到服务器:
检查我们是否真的可以获得我们想要的文件。如果可以,就开始加载。
Start()
{
try
{
using (WebClient client = new WebClient())
{
using (Stream stream = client.OpenRead("http://myserver.com"))
{
Debug.Log("Connected to server");
InitiateLoad();
}
}
}
catch
{
Debug.Log("Failed to connect to server");
}
}
检查持久数据中的文件:我在此阶段实施了 2 个步骤。首先,如果文件在持久数据中不存在,我们要加载视频;其次,如果文件存在,但与服务器上的文件大小不匹配,则重新下载文件。这样做的原因是,如果说用户在下载过程中退出应用程序,那么该文件将存在于持久数据中,但不会是完整的。
private void InitiateLoad()
{
if (!Directory.Exists(Application.persistentDataPath + "/" + folderPath))
{
Debug.Log("Domain Does Not Exsist");
Directory.CreateDirectory(Application.persistentDataPath + "/" + folderPath);
}
if(!File.Exists(URI))
{
SetupLoader();
}
else
{
long existingFileSize = new FileInfo(path).Length;
long expectedFileSize = 0;
string url = "http://myserver.com/" + folderPath + URI;
System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
int ContentLength;
if(int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
expectedFileSize = ContentLength;
}
}
if(existingFileSize != expectedFileSize)
{
SetupLoader();
}
}
}
开始加载:如果我们需要加载内容,则调用此函数。
private void SetupLoader()
{
string query = "GET " + "/" + folderPath + URIToLoad.Replace(" ", "%20") + " HTTP/1.1\r\n" +
"Host: "http://myserver.com"\r\n" +
"User-Agent: undefined\r\n" +
"Connection: close\r\n" +
"\r\n";
if (!Directory.Exists(Application.persistentDataPath + "/" + folderPath))
{
Directory.CreateDirectory(Application.persistentDataPath + "/" + folderPath);
}
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
client.Connect(http://myserver.com", 80);
networkStream = new NetworkStream(client);
var bytes = Encoding.Default.GetBytes(query);
networkStream.Write(bytes, 0, bytes.Length);
var bReader = new BinaryReader(networkStream, Encoding.Default);
string response = "";
string line;
char c;
do
{
line = "";
c = '\u0000';
while (true)
{
c = bReader.ReadChar();
if (c == '\r')
break;
line += c;
}
c = bReader.ReadChar();
response += line + "\r\n";
}
while (line.Length > 0);
Regex reContentLength = new Regex(@"(?<=Content-Length:\s)\d+", RegexOptions.IgnoreCase);
// Get the total number of bytes of the file we are downloading
contentLength = uint.Parse(reContentLength.Match(response).Value);
fileStream = new FileStream(Application.persistentDataPath + "/" + folderPath + URIToLoad, FileMode.Create);
totalDownloaded = 0;
contentDownloading = true;
}
下载:开始下载!请注意,如果您想暂停,只需更改 contentDownloading 布尔值。
private void Update()
{
if (contentDownloading)
{
byte[] buffer = new byte[1024 * 1024];
if (totalDownloaded < contentLength)
{
if (networkStream.DataAvailable)
{
read = (uint)networkStream.Read(buffer, 0, buffer.Length);
totalDownloaded += read;
fileStream.Write(buffer, 0, (int)read);
}
int percent = (int)((totalDownloaded/(float)contentLength) * 100);
Debug.Log("Downloaded: " + totalDownloaded + " of " + contentLength + " bytes ..." + percent);
}
else
{
fileStream.Flush();
fileStream.Close();
client.Close();
Debug.Log("Load Complete");
LoadNextContent();
}
}
}
希望这会有所帮助:)