从网络下载文件并保存至本地,及其文件的读取

最近因工作需要做了一个需求如下的功能:从网络下载图片,保存到本地,版本号不同时,更新本地文件,否则每次只从本地读取文件。
1、首先需要三个string类型的变量和一个WWW
WWW www = null;
string m_localPath = string.Format("{0}/LocalDirectory", Application.persistentDataPath);
string m_localKey = "LocalKey";
string m_localFilePath = string.Empty;

UITexture m_texture = null;//这是一个NGUI的UITexture,需要在代码中关联,此处不细表
2、下面介绍具体实现方法
void DownLoadFunction(string url, int version)
{
	if(!Directory.Exists(m_localPath))
	{
		Directory.CreatDirectory(m_localPath);
	}
	//取文件名
	string[] tempArray = url.Split(new char[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
	string tempPictureName = string.Empty;
	if(tempArray != null)
	{
		tempPictureName = tempArray[tempArray.Length - 1];
	}
	m_localFilePath = string.Format("{0}/{1}", m_localPath, tempPictureName);
	if(PlayerPerfs.HasKey(m_localKey) && PlayerPrefs.GetInt(m_localKey) == version && File.Exists(m_localFilePath))
	{
		www = new WWW(GetResDirByPath(m_localFilePath));
	}
	else
	{
		www = new WWW(url);
		PlayerPrefs.SetInt(m_localKey, version);
	}
}
3、下面是一个读取本地文件时的一个路径转换方法
voidGetResDirByPath(string path)
{
	string strBaseDir = string.Empty;
	if(RuntimePlatform.Android == Application.platform)
	{
		strBaseDir = "file:///" + path;
	}
	else if(RuntimePlatform.IPhonePlayer == Application.platform)
	{
		strBaseDir = "file://" + path;
	}
	else if(RuntimePlatform.WindowsWebPlayer == Application.platform ||RuntimePlatform.OSXWebPlayer == Application.platform))
	{
		strBaseDir = path;
	}
	else
	{
		strBaseDir = "file:///" + path;
	}
	return strBaseDir;
}
4、下面是每个游戏中都会存在的Update方法。
void Update()
{
	if(www != null)
	{
		if(www.error != null)
		{
			Debug.LogError(www.error + "FROM URL:" + www.url);
			www = null;
		}
		else if(www.isDone && www.progress == 1)
		{
			File.WriteAllBytes(m_localFilePath, www.texture.EncodeToPNG());
			m_texture.mainTexture = www.texture;
			www.Dispose();
			www = null;
		}
	}
}
5、以上就是针对此功能的主要功能代码,部分内容需要自己去查找和理解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值