服务器下载和本地保存

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

public class DowloadVideo : MonoBehaviour
{
    //http://www.unity3d.com/webplayers/Movie/sample.ogg
    private void Start()
    {
        StartCoroutine(DownloadAndSave("http://www.unity3d.com/webplayers/Movie/sample.ogg", "a2.ogg"));
    }

    /// <summary>  
    /// 下载并保存资源到本地  
    /// </summary>  
    /// <param name="url"></param>  
    /// <param name="name"></param>  
    /// <returns></returns>  
    public static IEnumerator DownloadAndSave(string url, string name, Action<bool, string> Finish = null)
    {
        url = Uri.EscapeUriString(url);
        string Loading = string.Empty;
        bool b = false;
        WWW www = new WWW(url);
        if (www.error != null)
        {
            print("error:" + www.error);
        }
        while (!www.isDone)
        {
            Loading = (((int)(www.progress * 100)) % 100) + "%";
            if (Finish != null)
            {
                Finish(b, Loading);
            }
            yield return 1;
        }
        if (www.isDone)
        {
            Loading = "100%";
            byte[] bytes = www.bytes;
            b = SaveAssets(Application.streamingAssetsPath, name, bytes);
            if (Finish != null)
            {
                Finish(b, Loading); 
            }
            Debug.Log(Loading);
        }
    }
    /// <summary>  
    /// 保存资源到本地  
    /// </summary>  
    /// <param name="path"></param>  
    /// <param name="name"></param>  
    /// <param name="info"></param>  
    /// <param name="length"></param>  
    public static bool SaveAssets(string path, string name, byte[] bytes)
    {
        Stream sw;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            try
            {
                sw = t.Create();
                sw.Write(bytes, 0, bytes.Length);
                sw.Close();
                sw.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值