Hi everyone,
I’m encountering an issue with resuming downloads using UnityWebRequest in Unity. Despite receiving a 206 Partial Content response from the server, the download progress starts from 0% instead of reflecting the already downloaded portion of the file.
Here’s what I’ve done so far:
- Range Header: Set the
Rangeheader to request the remaining bytes of the file. - Manual Progress Calculation: Calculated progress manually by adding the existing file length to the downloaded bytes.
- Server Response: Verified that the server responds with
206 Partial Content.
Code Snippet:
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using System.Collections;
using UnityEngine.UI;
public class DownloadManager : MonoBehaviour
{
public string url = “https://example.com/largefile.zip”;
public string savePath = “path/to/save/largefile.zip”;
public Slider progressBar; // UI element to show progress
IEnumerator Start()
{
yield return StartCoroutine(DownloadFile(url, savePath));
}
IEnumerator DownloadFile(string url, string savePath)
{
long fileLength = 0;
if (File.Exists(savePath))
{
FileInfo fileInfo = new FileInfo(savePath);
fileLength = fileInfo.Length;
}
UnityWebRequest request = UnityWebRequest.Get(url);
if (fileLength > 0)
{
request.SetRequestHeader("Range", "bytes=" + fileLength + "-");
}
request.downloadHandler = new DownloadHandlerFile(savePath, true);
request.SendWebRequest();
while (!request.isDone)
{
// Calculate progress manually
long totalBytes = fileLength + request.downloadedBytes;
long totalFileSize = fileLength + long.Parse(request.GetResponseHeader("Content-Length"));
float progress = (float)totalBytes / (float)totalFileSize;
progressBar.value = progress;
yield return null;
}
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + request.error);
}
else if (request.responseCode == 206) // Partial Content
{
Debug.Log("Resumed download complete");
}
else if (request.responseCode == 200) // OK
{
Debug.Log("Download started from the beginning");
}
else
{
Debug.Log("Download complete");
}
}
}