UnityWebRequest图片上传和下载

上传

 IEnumerator UpLoadTexture(byte[] bytes)
    {
        WWWForm form = new WWWForm();
        string id = "Photo_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");       
        form.AddField("id", id);//文件名这个参数是给服务器处理的,服务器不同,参数数量和类型也将不同
        form.AddBinaryData("Photo", bytes, "photo.jpg");
        using (UnityWebRequest www = UnityWebRequest.Post("http://localhost:8090/Default.aspx", form))
        {
            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log("上传失败:"+www.error);
            }
            else
            {
                string text = www.downloadHandler.text;
                Debug.Log("服务器返回值" + text);//正确打印服务器返回值
                Debug.Log("上传成功!");
            }
        }
    }

加载

  Texture2D texture2D;
    IEnumerator LoadTexture(string url, Image image)
    {
        print(url);
        using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url))
        {
            yield return uwr.SendWebRequest();

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log("图片加载失败"+uwr.error);
            }
            else
            {
                // Get downloaded asset bundle
                texture2D = DownloadHandlerTexture.GetContent(uwr);
                print("图片获取成功!");
                Sprite temp = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
                image.sprite = temp;
            }
        }
    }
posted @ 2022-06-22 18:04  哒哒哒~~~  阅读(314)  评论(0编辑  收藏  举报