0

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);
    }
}
vernou
  • 6,818
  • 5
  • 30
  • 58

1 Answers1

3
  • You have wrong file name so give filename with extension,
  • If you don't give extension, 'Directory.Exists' doesn't know whether file or directory.
  • or you could separate parameters such as rootDirPath and filename.
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 
        }
    }
}
vernou
  • 6,818
  • 5
  • 30
  • 58
Brian Choi
  • 733
  • 5
  • 14