如何访问保存在服务器和本地的文件?

时间:2018-09-12 19:14:26

标签: c# unity3d

我正在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;
}

1 个答案:

答案 0 :(得分:0)

我尝试了Internet上的多种解决方案,最后通过使用以下代码找到了正确的方法来下载和保存文件:

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