如何获取网络请求的上传进度



尝试使用Net.Http.Handlers命名空间中的progressMessageHandler,但我得到了

类型或命名空间名称"Handlers"在命名空间"System.Net.Http"中不存在(是否缺少程序集引用?(

我尝试过的东西:

  • Visual studio的Add引用。不起作用的事业团结下载System.Net.Http dll并将其放在unity dll中。不太正常的

  • 从nuget 更新System.Net.Http

我当前的代码是:

public static async Task<string> Upload(string uri, string pathFile)
{
byte[] bytes = System.IO.File.ReadAllBytes(pathFile);
using (var content = new ByteArrayContent(bytes))
{
content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
//Send it
var response = await nftClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}

我只需要使用UnityWebRequest并使用uploadProgress来更新进度:

UnityWebRequest uwr;
void Start()
{
StartCoroutine(PutRequest("http:///www.yoururl.com"));
StartCoroutine(UploadProgressCoroutine());
}
IEnumerator PutRequest(string url)
{
byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("Hello, This is a test");
uwr = UnityWebRequest.Put(url, dataToPut);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
IEnumerator UploadProgressCoroutine()
{
while (!uwr.isDone)
{
HandleProgress(uwr.uploadProgress);
yield return null;
}
}
void HandleProgress(float currentProgress)
{
// currentProgress is value between 0 and 1
}

基于程序员的代码。

或者,对于您的特定用例,您需要创建自己的UnityWebRequest,以按照服务器期望的方式获取标头和数据:

UnityWebRequest uwr;
void Start()
{
StartCoroutine(PostRequest("http:///www.yoururl.com", "/file/path/here"));
StartCoroutine(UploadProgressCoroutine());
}
IEnumerator PostRequest(string url, string filePath)
{
byte[] dataToPost = System.IO.File.ReadAllBytes(filePath);
uwr = new UnityWebRequest(url, "POST", new DownloadHandlerBuffer(),
new UploadHandlerRaw(dataToPost));
uwr.SetRequestHeader("Content-Type", "*/*");
uwr.SetRequestHeader("Accept", "application/json"); 
uwr.SetRequestHeader("Authorization", "Bearer " + apiToken);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
IEnumerator UploadProgressCoroutine()
{
while (!uwr.isDone)
{
HandleProgress(uwr.uploadProgress);
yield return null;
}
}
void HandleProgress(float currentProgress)
{
// currentProgress is value between 0 and 1
}

最新更新