首页 > 解决方案 > 如何访问保存在服务器和本地的文件?

问题描述

我正在 Unity 上开发 iOS 应用程序。最终,该应用程序应该能够下载、导入和加载保存在我的网站服务器上的 .obj 文件。但我目前正在本地开发,因此文件保存在我的笔记本电脑文件系统(我网站的本地服务器端)中。

我的问题是我应该使用什么来访问这些文件。我使用 WWW 来访问它,但它似乎不起作用。请在下面查看我的代码。

public void OnClick()
     {  
        StartCoroutine(ImportObject());
     } 

IEnumerator ImportObject (){
           Debug.Log("being called");

    WWW www = new WWW("http://localhost:8080/src/server/uploads/user-id/file name");
    Debug.Log("being called");

    yield return www;

    Debug.Log("NOT BEING CALLED !");

    **//Everything below here seems not being called...**

    if (string.IsNullOrEmpty(www.error)) {
        Debug.Log("Download Error");
    } else {
        string write_path = Application.dataPath + "/Objects/";
        System.IO.File.WriteAllBytes(write_path, www.bytes);
        Debug.Log("Success!");
    }

    GameObject spawnedPrefab;
    Mesh importedMesh = objImporter.ImportFile(Application.dataPath + "/Objects/");
    spawnedPrefab = Instantiate(emptyPrefabWithMeshRenderer);
    spawnedPrefab.transform.position = new Vector3(0, 0, 0);
    spawnedPrefab.GetComponent<MeshFilter>().mesh = importedMesh;
}

标签: c#unity3d

解决方案


我从互联网上尝试了多种解决方案,最后找到了正确的方法来下载并使用以下代码保存文件:

IEnumerator DownloadFile(string url) {

        var docName = url.Split('/').Last(); 
        var uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);

        string modelSavePath = Path.Combine(Application.dataPath, "Objects");
        modelSavePath = Path.Combine(modelSavePath, docName);

        //Create Directory if it does not exist
            if (!Directory.Exists(Path.GetDirectoryName(modelSavePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(modelSavePath));
            }

        var dh = new DownloadHandlerFile(modelSavePath);
        dh.removeFileOnAbort = true; 
        uwr.downloadHandler = dh;  

        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
            Debug.LogError(uwr.error);
        else
            Debug.Log("File successfully downloaded and saved to " + modelSavePath);
    }

推荐阅读