Unity upload and download images to the Web server

If the film has not read my last article, please see: Unity and Web server Post, Get

First, upload and download pictures

Unity of WWW can not only upload and download data in the form of text, you can also upload and download pictures, but during transmission, the information required picture into text format.

1. Create a RawImage in Unity and add a script in WebManager.cs Texture2D attribute used to store picture information, a String attribute access address of the local picture is loaded, a RawImage property displays upload pictures:
string PicturePath = @"file://C:\Users\Administrator\Desktop\vip.jpg";

public RawImage myRaw;

public Texture2D m_uploadImage;
Images associated with m_uploadImage 2. Create a local load pictures WebManager.cs script method to load the picture in Awake initialized, loaded, we only need to m_uploadImage behind this picture can be uploaded to the server:
private void Awake()
{
        StartCoroutine(ReadPic());
}

IEnumerator ReadPic()
{
	WWW www = new WWW(PicturePath);
	yield return www;
    if (www.error != null)
    {
    	m_info = www.error;
        yield return null;
    }
    m_uploadImage = www.texture;
}
3. Add Upload a method and a reading method WebManager.cs follows:
/// <summary>
    /// 服务器下载图片
    /// </summary>
    /// <returns></returns>
    IEnumerator DownLoadPic()
    {
        WWW www = new WWW("http://127.0.0.1:8088/upload/xxx.png");
        yield return www;
        if (www.error != null)
        {
            Debug.LogError(www.error);
            yield return null;
        }
        myRaw.texture = www.texture;
    }

    /// <summary>
    /// 图片上传服务器
    /// </summary>
    /// <returns></returns>
    IEnumerator IRequestPic()
    {
        WWWForm form = new WWWForm();
        form.AddField("folder","upload/");
        form.AddBinaryData("Pic", m_uploadImage.EncodeToPNG(),"xxx.png","image/png");
        WWW www = new WWW("http://127.0.0.1:8088/index.php", form);
        yield return www;
        if (www.error != null)
        {
            Debug.LogError(www.error);
            yield return null;
        }
        if (www.isDone)
        {
            Debug.LogError("上传成功");
            StartCoroutine(DownLoadPic());
        }
        Debug.LogError(www.text);
    }

In this code, upload, we will use the function EncodeToPNG pictures turn out for the byte array, use WWWForm way uploaded to the Web server, and before the difference is, this time to upload PNG format images. When the upload is complete in loading the picture.

4. Add OnGUI upload and download the code and modifying the parameters of the original Rect
 private void OnGUI()
    {
        GUI.BeginGroup(new Rect(Screen.width * 0.5f - 100,Screen.height * 0.5f -100,500,200),"");

        GUI.Label(new Rect(10,10,400,30),m_info);

        if (GUI.Button(new Rect (10,50,150,30),"GetData"))
        {
            StartCoroutine(IGetData());
        }

        if (GUI.Button(new Rect(10,80,150,30),"Post Data"))
        {
            StartCoroutine(IPostData());
        }

        if (GUI.Button(new Rect(10, 110, 150, 30), "上传 Image"))
        {
            StartCoroutine(IRequestPic());
        }

        if (GUI.Button(new Rect(10, 140, 150, 30), "下载 Image"))
        {
            StartCoroutine(DownLoadPic());
        }
        GUI.EndGroup();
    }
5. Modify the code index.php
<?php
if ( isset($_GET['username']) && isset($_GET['password']) )
{
      echo 'username is '.$_GET['username'].' and password is '.$_GET['password']; 
}
else if ( isset($_POST['username']) && isset($_POST['password']) )
{
      echo 'username is '.$_POST['username'].' and password is '.$_POST['password'];
}
else if( isset($_FILES['Pic']))
{
      //$_FILES['字段名']['name'] 客户端文件的原名称。

      //$_FILES['字段名']['type'] 文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"。

      //$_FILES['字段名']['size'] 已上传文件的大小,单位为字节。

      //$_FILES['字段名']['tmp_name'] 文件被上传后在服务端储存的临时文件名,一般是系统默认。可以在php.ini的upload_tmp_dir 指定,但 用 putenv() 函数设置是不起作用的。

      //$_FILES['字段名']['error'] 和该文件上传相关的错误代码。['error'] 是在 PHP 4.2.0 版本中增加的。下面是它的说明:(它们在PHP3.0以后成了常量)

      $folder=$_POST["folder"];//根据表单字段接受文件夹的字符串信息
      $fileName=$_FILES["Pic"]["name"];//根据表单字段接收需要保存的文件名字
      $tmp=$_FILES["Pic"]["tmp_name"];
      $fil=$folder.$fileName;

      //下面这一段代码保存数据信息到文本,用来测试提交的字符串信息
      $file=fopen("test.txt","a+");
      fwrite($file,$folder."+");
      fwrite($file,$fileName."+");
      fwrite($file,$fil);
      fclose($file);
      //判断当期目录下的upload目录是否存在该文件
      if(!file_exists($fil))
      {	
           //如果upload目录不存在该文件则将文件上传到upload目录下
           move_uploaded_file($tmp,$fil);
      }
}
?>

Because Unity is uploaded a picture, so we use $ _FILES to get the picture, which is a PHP array, which 'tmp_name' is your temporary files location, we visit this location you can get an array of pictures.

6. Test as follows:

Here Insert Picture Description
When you click Upload Image
Here Insert Picture Description

Second, delete the server folder and create a server folder

1. Add a folder in WebManager.cs way to create a folder and a method to delete files
 /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="FolderName"></param>
    /// <returns></returns>
    IEnumerator CreatFolder(string FolderName)
    {
        WWWForm form = new WWWForm();
        form.AddField("CreateFolderName", FolderName);
        WWW www = new WWW("http://127.0.0.1:8088/index.php", form);
        yield return www;
        if (www.error != null)
        {
            m_info = www.error;
            yield return null;
        }

        m_info = www.text;
        if (www.isDone)
        {
            Debug.Log("创建文件夹完成");
        }
        Debug.LogError(www.text);
    }

    /// <summary>
    /// 删除文件夹
    /// </summary>
    /// <param name="FolderName"></param>
    /// <returns></returns>
    IEnumerator DelFolder(string FolderName)
    {
        WWWForm form = new WWWForm();
        form.AddField("DeleteFolderName", FolderName);
        WWW www = new WWW("http://127.0.0.1:8088/index.php", form);
        yield return www;
        if (www.error != null)
        {
            m_info = www.error;
            yield return null;
        }

        m_info = www.text;
        if (www.isDone)
        {
            Debug.Log("删除文件夹完成");
        }
        Debug.LogError(www.text);
    }
2. Add the following function code OnGUI
if (GUI.Button(new Rect(150, 110, 150, 30), "服务器创建文件夹"))
        {
            StartCoroutine(CreatFolder("NewFolder"));
        }

        if (GUI.Button(new Rect(150, 140, 150, 30), "服务器删除文件夹"))
        {
            StartCoroutine(DelFolder("NewFolder"));
        }
3. Modify the code for index.php
<?php
if ( isset($_GET['username']) && isset($_GET['password']) )
{
      echo 'username is '.$_GET['username'].' and password is '.$_GET['password']; 
}
else if ( isset($_POST['username']) && isset($_POST['password']) )
{
      echo 'username is '.$_POST['username'].' and password is '.$_POST['password'];
}
else if( isset($_FILES['Pic']))
{
      //$_FILES['字段名']['name'] 客户端文件的原名称。

      //$_FILES['字段名']['type'] 文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"。

      //$_FILES['字段名']['size'] 已上传文件的大小,单位为字节。

      //$_FILES['字段名']['tmp_name'] 文件被上传后在服务端储存的临时文件名,一般是系统默认。可以在php.ini的upload_tmp_dir 指定,但 用 putenv() 函数设置是不起作用的。

      //$_FILES['字段名']['error'] 和该文件上传相关的错误代码。['error'] 是在 PHP 4.2.0 版本中增加的。下面是它的说明:(它们在PHP3.0以后成了常量)

      $folder=$_POST["folder"];//根据表单字段接受文件夹的字符串信息
      $fileName=$_FILES["Pic"]["name"];//根据表单字段接收需要保存的文件名字
      $tmp=$_FILES["Pic"]["tmp_name"];
      $fil=$folder.$fileName;

      //下面这一段代码保存数据信息到文本,用来测试提交的字符串信息
      $file=fopen("test.txt","a+");
      fwrite($file,$folder."+");
      fwrite($file,$fileName."+");
      fwrite($file,$fil);
      fclose($file);
      //判断当期目录下的upload目录是否存在该文件
      if(!file_exists($fil))
      {	
           //如果upload目录不存在该文件则将文件上传到upload目录下
           move_uploaded_file($tmp,$fil);
      }
}
else if( isset($_POST['CreateFolderName']))
{
      $myFile = $_POST["CreateFolderName"];//获取要创建的文件夹名字
 
      //文件存储路径
 
      if(!file_exists($myFile))
      {
            //判断文件夹是否存在
    //42行 
            mkdir($myFile,0777);//创建文件夹,并指定权限为0777才可以上传文件保存进去
      }
}
else if( isset($_POST['DeleteFolderName']))

{
      $myFile = $_POST["DeleteFolderName"];

      //调用函数,传入路径

      deleteDir($myFile);
}
?>
<?php
//调用删除方法
 
      function deleteDir($dir)
      
{
    
            if (!$handle = @opendir($dir))//判断当前文件夹是否为根目录
    
                  {
        
                        return false;
    
                  }
    
            while (false !== ($file = readdir($handle)))//循环遍历当前文件夹
    
            {
        
                  if ($file !== "." && $file !== "..")
        
                  {   
                        //排除当前目录与父级目录
            
                        $file = $dir . '/' . $file;
           
                        if (is_dir($file))
            
                        {
                
                              deleteDir($file);//删除当前文件夹中的文件
            
                        }
            
                        else
            
                        {
                
                              @unlink($file);
            
                        }
        
                  }
    
            }
    
            @rmdir($dir);//删除文件夹

      }
?>
Published 62 original articles · won praise 5 · Views 3926

Guess you like

Origin blog.csdn.net/qq_42194657/article/details/103041487