unity-game-engineunitywebrequest

Downloading images and save to device


I having some issues here with UnityWebRequest. I tried to download and save the jpeg, but it seem that the download is a success but it does not save it, and does not show me Log from "saveToFile" function.

Did I did something wrong?

Here are my code.

public string folderPath;

void Start()
{
       folderPath = Application.persistentDataPath + "/" + FileFolderName;
}

IEnumerator DownloadingImage(Uri url2)
{
    Debug.Log("Start Downloading Images");

    using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
    {
        // uwr2.downloadHandler = new DownloadHandlerBuffer();
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log(uwr.error);
        }
        else
        {
             Debug.Log("Success");
             Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
             byte[] results = uwr.downloadHandler.data;
             saveImage(folderPath, results);
        }
    }
}

void saveImage(string path, byte[] imageBytes)
{
    //Create Directory if it does not exist
    if (!Directory.Exists(Path.GetDirectoryName(path)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(path));
        Debug.Log("Creating now");
    }
    else
    {
        Debug.Log(path + " does exist");
    }

    try
    {
        File.WriteAllBytes(path, imageBytes);
        Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
    }
    catch (Exception e)
    {
        Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
        Debug.LogWarning("Error: " + e.Message);
    }
}

Solution

  • IEnumerator DownloadingImage(Uri url2)
    {
        Debug.Log("Start Downloading Images");
    
        using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
        {
            // uwr2.downloadHandler = new DownloadHandlerBuffer();
            yield return uwr.SendWebRequest();
    
            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                    Debug.Log("Success");
                    Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
                    byte[] results = uwr.downloadHandler.data;
                    string filename = gameObject.name+".dat";
                    // saveImage(folderPath, results);            // Not a folder path
                    saveImage(folderPath+"/"+filename, results);  // give filename 
            }
        }
    }