【Unity3d】如何实现移动端大文件上传(500M以上)

【Unity3d】移动端大文件上传
我们常常使用UnitywebRequest来完成与后端的通信工作

通常情况使用WWWForm上传文件以及附加字段,这种方式会把所有文件读到内存同时拼合所需字段,再上传云端,如果是文件体积比较小,这确实很方便,也是大多数人采用的方式;一旦文件体积较大,在移动端全部读取到内存中便会引发性能问题,轻则卡顿,重则闪退;

经过调研发现可以采用UnityWebRequest的UploadHandlerFile来解决大文件上传的问题,这是一种流式上传的方式,具体实现如下:

    public IEnumerator UploadLargeFile(string filePath, string url)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError($"File does not exist: {filePath}");
            yield break;
        }

        Debug.Log($"Uploading file: {filePath} to {url}");

        using (UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
        {
            request.uploadHandler = new UploadHandlerFile(filePath);
            request.downloadHandler = new DownloadHandlerBuffer();

            // Optional: Set Content-Type if required by the server
            request.SetRequestHeader("Content-Type", "application/octet-stream");
            request.SetRequestHeader("Authorization", SystemGlobal.Token);

            Debug.Log("发送请求");
            yield return request.SendWebRequest();
            Debug.Log("请求已发送");
            Debug.Log($"Response Code: {request.responseCode}");
            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("File uploaded successfully!");
                Debug.Log($"Response: {request.downloadHandler.text}");
            }
            else
            {
                Debug.LogError($"Upload failed: {request.error}");
                Debug.LogError($"Response: {request.downloadHandler.text}");
            }
        }
    }

另外:我们无法通过wequest.uploadProgress获取上传的进度,据资料显示底层未实现相关的逻辑—

不要忘记让后端的小伙伴配合修改解析方式哟~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值