Unity实现将图片上传到服务器功能
前言
今天在整理电脑里面工程的时候,我无意中翻出了之前做过的雀巢拍照项目。这个项目是我当时去北京上班时候第一次做过的完整的项目,也是花费了我的九牛二虎之力才将其完成。在我之前做的雀巢自拍项目中,其中有一个功能是将拍照存到软件文件夹中的图片上传到服务器上的功能。在这里我将这个功能记录在这里,分享给大家。
步骤
一、这个功能十分简单,使用的www的功能进行数据传输,具体代码如下所示:
using System.Collections;
//using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class UploadImage : MonoBehaviour
{
public Image image0;
/// <summary>
/// 上传到服务器的地址
/// </summary>
string url = "";
public string path = "";
public string path1 = "";
//配置文件管理类
public ConfigTest configTest;
private void Start()
{
url = configTest.dic["WebUrl"]["Url"];
}
/// <summary>
/// 上传图片到服务器
/// </summary>
public void ShangChuanImage()
{
path = System.DateTime.Now.ToString("yyyyMMddhhmmss");
path1 = path + ".PNG";
//Debug.Log("上传");
StartCoroutine(UnLoadImage(path));
}
/// <summary>
/// 上传到服务器
/// </summary>
/// <param name="path0"></param>
/// <returns></returns>
IEnumerator UnLoadImage(string path0)
{
yield return new WaitForEndOfFrame();
try
{
byte[] bytes = image0.sprite.texture.EncodeToPNG();
WWWForm form = new WWWForm();
form.AddField("Name", path0);
form.AddBinaryData("post", bytes);
WWW www = new WWW(url, form);
StartCoroutine(PostData(www));
}
catch (Exception e)
{
//Debug.Log("出现异常:" + e);
}
//Destroy(tex);
}
/// <summary>
/// 返回服务器信息
/// </summary>
/// <param name="www"></param>
/// <returns></returns>
IEnumerator PostData(WWW www)
{
yield return www;
Debug.Log(www.text);
}
}
二、将代码挂载到场景中的物体上,即可实现将图片上传到服务器的功能: