0

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

Fraccas
  • 15
  • 5
  • did you try `copy` and `move_uploaded` one at a time? What if both succeed? I don't really understand why `base64` .. binary image data is no `base64 string`, right ...? – derHugo Nov 20 '19 at 06:20
  • Yes, I've tried them separately. – Fraccas Nov 20 '19 at 06:22
  • A tutorial suggested using Convert.ToBase64String(imageData). I just wanted to state that I've tried that as an option as well. – Fraccas Nov 20 '19 at 06:24
  • Can you show where you get `imageData` from? – derHugo Nov 20 '19 at 06:24
  • @derHugo Yes, the post has been updated. – Fraccas Nov 20 '19 at 06:28
  • So the Unity part seems actually fine to me also the [`FileBrowserHelpers.ReadBytesFromFile`](https://github.com/yasirkula/UnitySimpleFileBrowser/blob/master/Assets/Plugins/SimpleFileBrowser/Scripts/FileBrowserHelpers.cs). But I'm no web and php expert ^^ It seems the request itself works just fine. So I guess the issue is the image was stored in the according position on the server but the data is broken? – derHugo Nov 20 '19 at 06:43
  • The `base64` thing was from [this thread](https://forum.unity.com/threads/2-simple-scripts-to-upload-files-to-a-http-server-and-free-hosting-recommendation.144261/) I guess ;) but is was actually only mentioned for *comparing* two files not for storing. – derHugo Nov 20 '19 at 06:47
  • https://stackoverflow.com/questions/26679468/how-to-recieve-an-image-file-with-php-that-was-submitted-over-a-post-request it was this one. So I enabled ini_set('display_errors',1); in php and got a new error message returned to Unity. I'll update my question with the new info. – Fraccas Nov 20 '19 at 06:54
  • 1
    so the error seems fairly clear, the php file is saying is not in 'images/something' probably because images is a partial path.. where exactly is images? – BugFinder Nov 20 '19 at 09:31
  • @BugFinder yeah, the target path was not correctly set. I added my answer below. – Fraccas Nov 20 '19 at 17:55

1 Answers1

0

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.

Fraccas
  • 15
  • 5