【问题标题】:Downloading images and save to device下载图像并保存到设备
【发布时间】:2020-06-11 06:34:41
【问题描述】:

我在使用 UnityWebRequest 时遇到了一些问题。 我尝试下载并保存jpeg,但似乎下载成功但没有保存,并且没有显示“saveToFile”功能的日志。

我是不是做错了什么?

这是我的代码。

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);
    }
}

【问题讨论】:

    标签: unity3d unitywebrequest


    【解决方案1】:
    • 您的文件名错误,因此请提供带有扩展名的文件名,
    • 如果不提供扩展名,'Directory.Exists' 不知道是文件还是目录。
    • 或者您可以分开参数,例如 rootDirPath 和文件名。
    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 
            }
        }
    }
    

    【讨论】:

    • 感谢您回答我的问题并纠正我的错误。
    猜你喜欢
    • 2011-01-30
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多