유니티에서 이미지 파일 업로드 또는 다운로드 관련 예제입니다. 참고로 이대로 실행하면 아무런 동작을 하지 않으므로 자신의 필요에 맞게 수정해서 사용해야 합니다.



using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using MiniJSON;
using System.Xml;
using System.RegularExpressions;

public class WebSample : MonoBehaviour {
    public Transform grid;
    public GameObject itemPrefab;
    public string defaultURL = "http://yourdomain.com";

    void FileUpload(string path, string fname, int width, int height)
    {
        if (!File.Exists(path)) return;
        byte[] bytes = File.ReadAllBytes(path);
        WWWForm form = new WWWForm();
        form.AddField("file", fname);
        form.AddField("width", width.ToString());
        form.AddField("height", height.ToString());
        form.AddBinaryData("myfile", bytes, fname, "image/png");
        WWW web = new WWW(defaultURL + "/upload", form);
        StartCoroutine(WebAction(web, () =>
        {
            // Upload Ok!
        }));
    }

    void FileUpload(Texture2D texture, string fname)
    {
        byte[] bytes = texture.EncodeToPNG();
        WWWForm form = new WWWForm();
        form.AddField("file", fname);
        form.AddField("width", texture.width.ToString());
        form.AddField("height", texture.height.ToString());
        form.AddBinaryData("myfile", bytes, fname, "image/png");
        WWW web = new WWW(defaultURL + "/upload", form);
        StartCoroutine(WebAction(web, () =>
        {
            // Upload Ok!
        }));
    }

    void FileDownload()
    {
        WWWForm form = new WWWForm();
        form.AddField("page", 1);
        WWW web = new WWW(defaultURL + "/download", form);
        StartCoroutine(WebAction(web, () =>
        {
            List<object> jsonData = (List<object>)Json.Deserialize(web.text);
            int total = jsonData.Count;
            foreach (Dictionary<string, object> row in jsonData)
            {
                string url = defaultURL + row["url"].ToString();
                string file = row["file"].ToString();
                int width = int.Parse(row["width"].ToString());
                int height = int.Parse(row["height"].ToString());
                GameObject go = Instantiate(itemPrefab) as GameObject;
                Transform tf = go.transform;
                Text titleText = go.GetComponentInChildren<Text>();
                tf.SetParent(grid);
                tf.localScale = Vector3.one;
                titleText.text = file;
                ShowSprite(url, go);
            }
        }));
    }

    void ShowSprite(string url, GameObject go)
    {
        WWW web = new WWW(url);
        StartCoroutine(WebAction(web, () =>
        {
            Texture2D tex = web.texture;
            Image img = go.GetComponentInChildren<Image>();
            SpriteRenderer sr = go.GetComponentInChildren<SpriteRenderer>();
            Sprite s = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100f);
            if (img != null) img.sprite = s;
            if (sr != null) sr.sprite = s;
        }));
    }

    IEnumerator WebAction(WWW web, System.Action callback)
    {
        yield return web;
        if (web.error != null)
        {
            Debug.Log("WebAction Error : " + web.error);
        }
        else
        {
            Debug.Log("WebAction Ok!");
            callback();
        }
    }
}

<?php

$uploads_dir = '/uploads';

if (isset($_FILE["myFile"])) {
    $tmp_name = $_FILES['myFile']['tmp_name'];
    $file_name = $_FILES['myFile']['name'];
    $file_path = $uploads_dir . "/" . $file_name;
    move_uploaded_file($tmp_name, $file_path);

    $conn = mysql_connect("HOST", "USER", "PASSWORD");
    mysql_select_db("DATABASE", $conn);
    $sql = "INSERT INTO filetable (name, width, height) VALUES ('$file_name', '$width', '$height')";
    $q = mysql_query($query);
    mysql_close($conn);
}

<?php

$conn = mysql_connect("HOST", "USER", "PASSWORD");
mysql_select_db("DATABASE", $conn);
$sql = "SELECT * FROM filetable LIMIT 10";
$q = mysql_query($sql);
$result = array();
while ($row = mysql_fetch_array($q, MYSQL_ASSOC))
    $result[] = $row;
echo json_encode($result);
mysql_close($conn);

    void GetTopFreeApps()
    {
        WWW web = new WWW("https://itunes.apple.com/us/rss/topfreeapplications/limit=100/genre=6014/json");
        StartCoroutine(WWWActoin(web, () =>
        {
            Dictionary<string, object> jsonData = (Dictionary<string, object>)Json.Deserialize(web.text);
            Dictionary<string, object> feed = (Dictionary<string, object>)jsonData["feed"];
            List<object> entryList = (List<object>)feed["entry"];
            foreach (Dictionary<string, object> row in entryList)
            {
                string img = ((Dictionary<string, object>)((List<object>)row["im:image"])[2])["label"].ToString();
                string title = ((Dictionary<string, object>)row["title"])["label"].ToString();
                string url = ((Dictionary<string, object>)((Dictionary<string, object>)row["link"])["attributes"])["href"].ToString();
                string id = ((Dictionary<string, object>)((Dictionary<string, object>)row["id"])["attributes"])["im:bundleId"].ToString();
                string ctype = ((Dictionary<string, object>)((Dictionary<string, object>)row["im:contentType"])["attributes"])["label"].ToString();
                string category = ((Dictionary<string, object>)((Dictionary<string, object>)row["category"])["attributes"])["label"].ToString();
                string release = ((Dictionary<string, object>)((Dictionary<string, object>)row["im:releaseDate"])["attributes"])["label"].ToString();
                GameObject go = Instantiate(itemPrefab) as GameObject;
                Transform tf = go.transform;
                Text titleText = go.GetComponentInChildren<Text>();
                tf.SetParent(grid);
                tf.localScale = Vector3.one;
                titleText.text = title;
                ShowSprite(url, go);
            }
        }));
    }

    void GetTopFreeAppsXML()
    {
        string xml_url = "https://itunes.apple.com/us/rss/topfreeapplications/limit=100/genre=6014/xml";
        WWW web = new WWW(xml_url);
        StartCoroutine(WWWActoin(web, () =>
        {
            XmlDocument doc = new XmlDocument();
            string str = web.text.Trim().Replace("xmlns=\"", "xmlns2=\"");
            str = Regex.Replace(str, @"<(/?)im:", "<$1im_");
            doc.LoadXml(str);
            XmlNodeList entryList = doc.SelectNodes("feed/entry");
            foreach (XmlNode node in entryList)
            {
                string img = node.SelectNodes("im_image")[2].InnerText;
                string title = node.SelectSingleNode("title").InnerText;
                string url = node.SelectSingleNode("link").Attributes["href"].Value.ToString();
                string id = node.SelectSingleNode("id").Attributes["im:bundleId"].Value.ToString();
                string ctype = node.SelectSingleNode("im_contentType").Attributes["label"].Value.ToString();
                string category = node.SelectSingleNode("category").Attributes["term"].Value.ToString();
                string release = node.SelectSingleNode("im_releaseDate").Attributes["label"].Value.ToString();
                GameObject go = Instantiate(itemPrefab) as GameObject;
                Transform tf = go.transform;
                Text titleText = go.GetComponentInChildren<Text>();
                tf.SetParent(grid);
                tf.localScale = Vector3.one;
                titleText.text = title;
                ShowSprite(url, go);
            }
        }));
    }

2015/01/12 18:14 2015/01/12 18:14

댓글을 달아 주세요