我使用文件流来实现你正在尝试实现的功能。这样做的好处是可以很容易地实现暂停功能,实现进度条以及在数据被流式传输时运行其他计算。
我希望我能对下面的所有代码负责,但其中一些是修改后的代码,可以在这里找到:
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");
}
}
检查持久数据中的文件:在此阶段,我已经实施了两个步骤。首先,如果文件不存在于持久数据中,我们希望加载视频;其次,如果文件存在但与服务器上的文件大小不匹配,则重新下载文件。这样做的原因是,如果用户在下载过程中退出应用程序,则文件将存在于持久数据中,但不完整。
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:
"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:
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);
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();
}
}
}
希望这能帮到您 :)