How does Unity upload a file to the server

During the game development process, sometimes it is necessary to upload some files to the remote server, such as game resource files, player data, and so on. In Unity, we can use the UnityWebRequest class to implement the file upload function. This article will introduce in detail how Unity uploads a file to the server, and gives the core code implementation of Unity and the server.

right! There is a game development exchange group here, which gathers a group of zero-based beginners who love to learn games, and there are also some technical experts who are engaged in game development. You are welcome to exchange and learn.

  1. Create a scene for uploading files

First, we need to create a scene for uploading files in Unity. In this scenario, we can add a button that will trigger the file upload function when the user clicks the button. We also need to add a file selection box through which the user can select a file to upload.

  1. Implement file upload function

Next, we need to use the UnityWebRequest class to implement the file upload function. UnityWebRequest is a network request class in Unity, which can help us send HTTP requests and get response data. In the file upload function, we need to use UnityWebRequest to send a POST request, and send the file to be uploaded to the server as the request body. The following is the core code implementation of file upload:

IEnumerator UploadFile(string path, string url)
{
    // 读取要上传的文件
    byte[] bytes = File.ReadAllBytes(path);

    // 创建UnityWebRequest对象
    UnityWebRequest request = UnityWebRequest.Post(url, "POST");

    // 将要上传的文件作为请求体
    request.uploadHandler = new UploadHandlerRaw(bytes);

    // 设置请求头
    request.SetRequestHeader("Content-Type", "application/octet-stream");

    // 发送请求
    yield return request.SendWebRequest();

    // 处理响应数据
    if (request.isNetworkError || request.isHttpError)
    {
        Debug.Log(request.error);
    }
    else
    {
        Debug.Log("Upload complete!");
    }
}

In this code, we first use the File.ReadAllBytes method to read the content of the file to be uploaded and save it into a byte array. Then, we create a UnityWebRequest object with the file to be uploaded as the request body. We also set the request header and set the Content-Type to application/octet-stream, indicating that the upload is a binary file. Finally, we use the SendWebRequest method to send the request and process the response data.

  1. interact with the server

Finally, we need to implement an interface for receiving files on the server side, and call this interface in Unity to upload files. We can use PHP language to implement this interface. The following is the core code implementation on the server side:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

In this code, we first define a directory uploads for uploading files, and save the files to be uploaded to this directory. Then, we use the move_uploaded_file method to move the temporary file to the target file to complete the file upload operation.

In Unity, we can use the WWWForm class to build an HTTP request and add the file to be uploaded to the request. The following is the core code implementation of Unity interacting with the server:

public void Upload()
{
    string url = "http://localhost/upload.php";
    string path = fileInput.text;
    StartCoroutine(UploadFile(path, url));
}

In this code, we first get the file path in the input box and pass it as a parameter to the UploadFile method. Then, we use the StartCoroutine method to start a coroutine, and perform the file upload operation in the coroutine.

The code implementation of the complete Unity upload file is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using UnityEngine.UI;

public class FileUploader : MonoBehaviour
{
    public InputField fileInput;

    IEnumerator UploadFile(string path, string url)
    {
        // 读取要上传的文件
        byte[] bytes = File.ReadAllBytes(path);

        // 创建UnityWebRequest对象
        UnityWebRequest request = UnityWebRequest.Post(url, "POST");

        // 将要上传的文件作为请求体
        request.uploadHandler = new UploadHandlerRaw(bytes);

        // 设置请求头
        request.SetRequestHeader("Content-Type", "application/octet-stream");

        // 发送请求
        yield return request.SendWebRequest();

        // 处理响应数据
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Upload complete!");
        }
    }

    public void Upload()
    {
        string url = "http://localhost/upload.php";
        string path = fileInput.text;
        StartCoroutine(UploadFile(path, url));
    }
}

In this code, we use the UnityWebRequest class to implement the file upload function, and use the WWWForm class to construct the HTTP request. We also use the PHP language to implement the file upload interface on the server side. When using this code, we need to upload the PHP file to the web server and set the URL in Unity to the URL of the PHP file.

Summarize

This article introduces how Unity uploads a file to the server, and gives the core code implementation of Unity and the server. When using this code, we need to pay attention to some security issues, such as preventing malicious file uploads, limiting the size of uploaded files, and so on. We can also add some error handling mechanisms in the code, such as checking whether the file exists, checking whether the server is available, etc., to improve the robustness and reliability of the code.

Guess you like

Origin blog.csdn.net/voidinit/article/details/130205963