tech/metaverse

21/09/13 UnityWebRequest - Get, Save File 예제

tech-lover 2021. 9. 13. 10:45

- Get and then save file

 

```

using System.Collections;

using System.Collections.Generic;

using System.IO;

using UnityEngine;

using UnityEngine.Networking;

 

public class GetImageFromWeb : MonoBehaviour 

{  

    void Awake()

    {

       StartCoroutine(DownLoadGet("URL"));

    }

 

    public IEnumerator DownLoadGet(string URL)

    {

        UnityWebRequest request = UnityWebRequest.Get(URL);

        //해더 정보 필요시

        //request.SetRequestHeader("key", "timebox");

 

        yield return request.SendWebRequest();

 

        //에러 발생시

        if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError )

        {

            Debug.Log(request.error);

        }

        else

        {

            //다운로드 데이터를 파일로 저장

            SaveFile (request.downloadHandler.data);

        }

    }

 

    public void SaveFile(byte[] bytes)

    {

        string destination = Application.persistentDataPath + "/file.png";

        //private string destination = Application.persistentDataPath + "/file.png"; // android

        //string destination = "c:\file.png"; // for pc

 

        if(File.Exists(destination))

        {

            File.Delete (destination);

        }

            

        File.WriteAllBytes (destinationbytes);

 

        //Debug.Log(destination);

    }

}

```