首页 > 解决方案 > Saving photo to server with PHP from C# (Unity Game Engine)

问题描述

I'm currently working on a Unity Game Engine project in which I send a photo from the user's local computer within the game to a web server using PHP. My goal is to store the file path within a database and store the actual image on the server within a subdirectory.

I can successfully send the photo from Unity, and the PHP script is getting information about the photo (filename, size, tmp_name). However, I'm failing to actually store the photo on the server.

C# Unity Code

IEnumerator SendFile(byte[] imageData, string path)
    {

        WWWForm form = new WWWForm();
        string filename = Path.GetFileName(path);
        string filepathname = Data_Manager.steamID + "-" + Data_Manager.steamName + "-" + filename;


        form.AddBinaryData("userImage", imageData, filepathname, "image/png");
        form.AddField("steamID", Data_Manager.steamID);
        form.AddField("steamName", Data_Manager.steamName);

        using (UnityWebRequest www = UnityWebRequest.Post("http://www.roastpartygame.com/database/storeImage.php", form))
        {
            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                // Print response
                Debug.Log(www.downloadHandler.text);
            }
        }
    }

The code above works as expected, and anything I echo from PHP is logged within the Unity game using "Debug.Log(www.downloadHandler.text);" in the code above.

PHP

        $fileName = $_FILES['userImage']['name']; 
        $target = 'images/'.$fileName;

        //$base64decodedString = base64_decode(urldecode($_FILES['userImage']));
        //file_put_contents($target, file_get_contents($_FILES['userImage']['name']));

        if (copy($_FILES['userImage']['tmp_name']), $target) echo 'MOVED FILE!';
        if (move_uploaded_file($_FILES['userImage']['tmp_name'], $target)) echo 'MOVED FILE!';

I've played around with copy and move_uploaded_file. I've also experimented with using base64 but I'm having issues sending the photo using base64 from within the C# script in Unity. This was quite simple when submitting the photo from a form within a PHP page.

Anyone have any advice on how to store the image to the server?

Additional Code (Grabbing Photo Data in C# Unity):

public void DirectImageFolder()
    {
        FileBrowser.SetFilters(true, new FileBrowser.Filter("Images", ".jpg", ".png"));
        FileBrowser.SetDefaultFilter(".jpg");
        FileBrowser.SetExcludedExtensions(".lnk", ".tmp", ".zip", ".rar", ".exe");

        FileBrowser.AddQuickLink("Users", "C:\\Users", null);
        //FileBrowser.ShowLoadDialog((path) => {
            // Check if photo selected

        //},
        //() => { Debug.Log("Canceled"); },
        //false, null, "Roast Party: Select Image", "Select");

        StartCoroutine(ShowLoadDialogCoroutine());
    }

    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return FileBrowser.WaitForLoadDialog(false, null, "Roast Party: Load Image", "Load Image");

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        // upload image to server
        if (FileBrowser.Success)
        {
            // If a file was chosen, read its bytes via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);

            //send the binary data to web server
            StartCoroutine(SendFile(bytes, FileBrowser.Result));
        }
    }

A custom unity plugin is being used to grab the photo data.

Edit: I added "ini_set('display_errors',1); " to PHP and I'm getting this message now in Unity.

Warning: copy(images/76561198086846783-Fraccas-au.jpg): failed to open stream: No such file or directory in /hermes/walnaweb05a/b2967/moo.devfraccascom/roastparty/database/storeImage.php on line 11

标签: c#phpunity3dunitywebrequest

解决方案


Simple mistake of not correctly setting my target path. I needed to back out of the directory I was in, and go into the images folder.

if(isset($_FILES['userImage'])) { 
        $fileName = $_FILES['userImage']['name']; 
        $target = '../images/'.$fileName;

        if (copy($_FILES['userImage']['tmp_name'], $target)) echo 'MOVED FILE!';
}

"$target = '../images/'.$fileName;" instead of "$target = 'images/'.$fileName;"

The old php file for uploading photos from the website was sitting on the same directory as the images folder and I didn't realize the mistake.

Thanks for helping troubleshoot @derHugo.


推荐阅读