Implementing File Uploads to a Server in Unity3D

File Upload Mechanism in Unity

In standard web applications, file uploads work by bundling file data into a HTTP request and sending it via POST to the server, which then parses and saves the file. Unity follows the same principle using the WWW class or UnityWebRequest class for network communication.

Implementing Uploads with the WWW Class

The WWW clas provides basic HTTP functionality for uploading and downloading files.

Creating a WWW Request

string uploadUrl = "http://localhost/upload.php";
WWWForm dataPayload = new WWWForm();
datPayload.AddField("username", "player1");
dataPayload.AddBinaryData("uploadedFile", fileBytes, "savegame.dat", "application/octet-stream");
WWW request = new WWW(uploadUrl, dataPayload);

Awaiting and Processing Response

yield return request;

if (string.IsNullOrEmpty(request.error))
{
    Debug.Log("File sent successfully: " + request.text);
}
else
{
    Debug.LogError("Transfer failed: " + request.error);
}

The AddField method attaches non-file parameters, while AddBinaryData handles the actual file data with MIME type specification.

Implementing Uploads with UnityWebRequest

UnityWebRequest offers advanced features like compression and resumable transfers, introduced in Unity 5.2.

Setting Up the Request

string endpoint = "http://localhost/upload.php";
UnityWebRequest uwr = UnityWebRequest.Post(endpoint, formData);
uwr.SetRequestHeader("Content-Type", "multipart/form-data");
uwr.SetRequestHeader("Accept-Encoding", "gzip, deflate");
uwr.uploadHandler = new UploadHandlerRaw(fileContent);
uwr.uploadHandler.contentType = "application/octet-stream";
uwr.uploadHandler.fileName = "savegame.dat";

Sending and Handling Response

yield return uwr.Send();

if (uwr.isNetworkError || uwr.isHttpError)
{
    Debug.LogError("Request failed: " + uwr.error);
}
else
{
    Debug.Log("Upload completed: " + uwr.downloadHandler.text);
}

The UploadHandlerRaw class manages the raw binary data, with contentType defining the MIME type and fileName specifying the target filaname on the server.

Server-Side Implementation (PHP)

The server needs an endpoint to receive and store uploaded files.

<?php
$username = $_POST['username'];
$uploadedFile = $_FILES['uploadedFile'];
$destinationPath = 'uploads/' . basename($uploadedFile['name']);

if (move_uploaded_file($uploadedFile['tmp_name'], $destinationPath)) {
    echo 'File uploaded successfully';
} else {
    http_response_code(500);
    echo 'Upload failed';
}
?>

The $_POST array captures non-file parameters, while $_FILES contains the uploaded file metadata. The move_uploaded_file function safely transfers the temporary file to the designated directory.

Tags: Unity3D file-upload www-class unitywebrequest HTTP

Posted on Wed, 28 Oct 2026 16:46:25 +0000 by rcatal02