unity 文件上传 php接收

15 篇文章 1 订阅

unity

using UnityEngine;
using System.Collections;

public class SavePicture : MonoBehaviour
{
    string url = "http://localhost:8888/upload_file.php";
    string path;

    public Material image;
    void Start()
    {
        path = Application.dataPath + "/wukuaTurret.jpg";
    }
    void OnGUI()
    {
        if (GUI.Button(new Rect(100, 100, 100, 100), "SavePic"))
        {
            Debug.Log(path);
            StartCoroutine(getTexture2d());
        }
    }

    IEnumerator getTexture2d()
    {

        yield return new WaitForEndOfFrame();

        int width = Screen.width;
        int height = Screen.height;
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);
        tex.Apply();
        byte[] bytes = tex.EncodeToPNG();

        WWWForm form = new WWWForm();
        //form.AddField("Name", "pic1");
        form.AddBinaryData("file", bytes);
        //form.AddBinaryData("file", bytes, "hh.jpg", "image/png");
        WWW www = new WWW(url, form);
        StartCoroutine(PostData(www));
        Destroy(tex);
        System.IO.File.WriteAllBytes(path, bytes);

    }
    IEnumerator PostData(WWW www)
    {
        yield return www;
        Debug.Log("ok");
        Debug.Log(www.text);
    }
}

文件目录:

php  

<?php
$fileName =$_FILES["file"]["name"];
 
   if ($_FILES["file"]["error"] > 0)
    {
        echo "错误:: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
        echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
        echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>";
        
        // 判断当期目录下的 upload 目录是否存在该文件
        // 如果没有 upload 目录,你需要创建它,upload 目录权限为 777
        if (file_exists("upload/" . $fileName))
        {
            echo $fileName . " 文件已经存在。 ". "<br>";
            if (!unlink(("upload/" .$fileName))) {
            	echo "Error deleting $fileName". "<br>";
            }else{
            	echo ("Deleted $fileName"). "<br>";
            	echo "开始存储文件". "<br>";
            	// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
           		move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            	echo "文件存储在: " . "upload/" . $_FILES["file"]["name"]. "<br>";
            	
            }
        }
        else
        {
            // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            echo "文件存储在: " . "upload/" . $_FILES["file"]["name"]. "<br>";
        }
    }
?>

index.html

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

 

 

其他:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using RestSharp;
using System.Collections.Specialized;
using System.IO;
using System;
using System.Net;
using System.Linq;
using System.Threading;
using System.Text;

public class httpupload : MonoBehaviour {

    static Stream FileToStream(string fileName)
    {
        // 打开文件
        FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        // 读取文件的 byte[]
        byte[] bytes = new byte[fileStream.Length];
        fileStream.Read(bytes, 0, bytes.Length);
        fileStream.Close();
        // 把 byte[] 转换成 Stream
        Stream stream = new MemoryStream(bytes);
        return stream;
    }
    static string Upload(string url, string fileName)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        Stream postStream = new MemoryStream();
        #region 处理Form表单文件上传
        //通过表单上传文件
        string boundary = "----" + DateTime.Now.Ticks.ToString("x");
        string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"name\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n";
        try
        {
            //准备文件流
            using (var fileStream = FileToStream(fileName))
            {
                var formdata = string.Format(formdataTemplate, "", System.IO.Path.GetFileName(fileName) /*Path.GetFileName(fileName)*/);
                var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
                postStream.Write(formdataBytes, 0, formdataBytes.Length);

                //写入文件
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //结尾
        var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
        postStream.Write(footer, 0, footer.Length);
        request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

        #endregion

        request.ContentLength = postStream != null ? postStream.Length : 0;
        request.Accept = "*/*";
        //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
        request.KeepAlive = true;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

        #region 输入二进制流
        if (postStream != null)
        {
            postStream.Position = 0;
            //直接写入流
            Stream requestStream = request.GetRequestStream();
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
            postStream.Close();//关闭文件访问
        }
        #endregion

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
            {
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }
    }

    void Start () {

        string url = "http://********/api/";
        string filePath = "D:\\2.jpg";
        string result = Upload(url, filePath);
        Debug.Log(result);
        Application.OpenURL(result);
    }

    // Update is called once per frame
    void Update () {
		
	}
}

 

有两种方法可以在Unity中上传大文件。 第一种方法是使用HTTP协议,通过HTTP请求将文件上传到服务器。您可以使用Unity的WWW类或UnityWebRequest类来实现。在您提供的引用中,您可以看到一个使用UnityWebRequest类的示例代码。该代码将文件读取为字节数组,并使用AddBinaryData方法将其添加到请求中,然后通过Send方法发送请求。您可以根据需要修改代码中的文件路径、文件名和服务器URL。此方法适用于Unity5.4及更高版本。 另一种方法是使用FTP协议,在Unity中通过FTP将文件上传到服务器。您可以使用Unity的FTPWebRequest类来实现。您可以创建一个FTPWebRequest对象,并设置其相关属性,如远程服务器地址、用户名、密码等。然后,您可以使用GetRequestStream方法获取请求流,并将文件流写入请求流中。最后,使用GetResponse方法发送请求并获取服务器的响应。这种方法适用于Unity4及更高版本。 无论您选择哪种方法,都需要根据服务器的要求进行相应的配置,例如设置最大接收Size。这可以确保在传输大文件时,服务器能够正确接收文件。在您提供的引用中,提到了在WeApi接收方法中设置最大接收Size的问题。您可以根据服务器端的具体实现和框架来设置最大接收Size的参数。 总结:Unity中上传大文件的方法有两种,一种是使用HTTP协议,通过HTTP请求将文件上传到服务器;另一种是使用FTP协议,在Unity中通过FTP将文件上传到服务器。您可以根据具体情况选择合适的方法,并根据服务器要求进行相应的配置。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值