Unity使用UnityWebRequest上传文件到服务器的简单实现流程

Unity使用UnityWebRequest上传文件到服务器的简单实现流程

前言

我在以前的项目中写过有关上传图片到服务器的功能,但是没有写过上传其他类型的文件到服务器上的功能。今天为了实现一个上传gif图片的功能,我在网上查找资料,找到了一种使用UnityWebRequest上传文件的方法。这个方法真是太有用处了,可以说是什么文件都通用,于是我在这里赶紧记录一下,方便以后使用。

实现步骤

1.实现步骤很简单,以下是我自己很据网上的资料写的脚本,完成后将此脚本挂载到场景中的物体上,代码如下所示:

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


public class UpGifManager : MonoBehaviour
{
 
Unity使用UnityWebRequest上传文件到网站后,通常服务器会返回一个响应,其中包括文件服务器上存储的位置信息。这个位置通常是通过HTTP状态码、响应头或者响应体中的URL来指示的。然而,由于UnityWebRequest本身并不直接提供获取服务器存储路径的功能,你需要解析服务器的响应才能找到对应信息。 以下是一个基本流程: 1. **发送请求**:使用UnityWebRequest.UploadFile方法上传文件,并设置POST数据或包含文件的表单字段。 ```csharp using UnityEngine; using System.Collections; using UnityEngine.Net; public class FileUploader : MonoBehaviour { public string url = "http://yourwebsite.com/upload"; private UnityWebRequest request; void Start() { request = UnityWebRequest.Post(url, ""); request.uploadHandler = new UploadHandlerFile("file", Application.dataPath + "/YourFile.txt"); StartCoroutine(UploadAndProcessResponse()); } IEnumerator UploadAndProcessResponse() { yield return request.Send(); if (request.isNetworkError || request.isHttpError) Debug.LogError("Failed to upload file. Code: " + request.error); else { // Check for success code and parse response int statusCode = request.responseCode; if (statusCode == 200) // Successful upload { string responseJson = request.downloadHandler.text; // Assuming JSON response dynamic responseObject = JsonUtility.FromJson(responseJson, typeof(object)); string storagePath = responseObject.storageLocation; // Extract the path from response Debug.Log("Uploaded file stored at: " + storagePath); } } } } ``` 2. **解析响应**:假设服务器返回的是JSON格式,你可以使用JsonUtility从响应体中提取存储路径。如果不是JSON,检查响应头的Content-Disposition字段可能会有线索。 3. **处理异常**:记得处理可能出现的网络错误或其他非成功状态码。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波波斯维奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值