最近研究了下http 從服務器下載到本地。
有點復雜,沒太搞明白 post, 不過也做了個demo......
用到了 2 種方式 :
1, http get
2, www
第一種:
http get
string urlPath = "http://www........";//寫個網絡資源路徑(自己寫)
string localPath = @"D:\BianZhen.mov";
/// <summary>
/// 下載文件
/// </summary>
IEnumerator DownLoadFile(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
HttpWebResponse hw = (HttpWebResponse)request.GetResponse();
Stream stream = hw.GetResponseStream();
FileStream fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write);
long length = hw.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 + "%");
}
currentnn = currentProgress;
yield return false;
}
hw.Close();
stream.Close();
fileStream.Close();
}
decimal currentNumShow;
GUIStyle guistyle = new GUIStyle();
void OnGUI()
{
guistyle.fontSize = 80;
GUI.Label(new Rect(50, 50, 50, 50), currentNumShow.ToString(), guistyle);
}
第二種:
www
string urlPath = "http://www.....";//資源網絡路徑(自己寫)
string file_SaveUrl = @"D:\test.rar";//資源保路徑
FileInfo file;
void Start ()
{
file = new FileInfo(file_SaveUrl);
Debug.Log(file_SaveUrl);
StartCoroutine(DownFile(urlPath));
}
/// <summary>
/// 下載文件
/// </summary>
IEnumerator DownFile(string url)
{
WWW www = new WWW(url);
yield return www;
if (www.isDone)
{
Debug.Log("下載完成");
byte[] bytes = www.bytes;
CreatFile(bytes);
}
}
/// <summary>
/// 創建文件
/// </summary>
/// <param name="bytes"></param>
void CreatFile(byte[] bytes)
{
Stream stream;
stream = file.Create();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
stream.Dispose();
}