【问题标题】:How to access file saved on server and local?如何访问保存在服务器和本地的文件?
【发布时间】:2018-09-16 04:26:52
【问题描述】:

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

【问题讨论】:

  • 你说你想从一个 url 下载模型,但你为什么要这样做:WWW("file://" + filePath);?
  • 错误是什么?您正在写入一个目录,并且您的 write_path 末尾没有文件名
  • @Programmer 很抱歉造成混乱。请查看更新的代码。它实际上是在接收存储在我本地主机中的文件的 url。
  • 当你写一个困惑的问题时,你很可能得不到任何答案。看看苍白问你什么。你有什么错误吗?什么是日志或请求? “下载错误”或“成功!” ?
  • 我没有收到任何错误,'yield return www;' 下面的所有内容根本没有被调用。我试图在 'yield return www' 之后添加 Debug.Log,但它没有被调用。

标签: c# unity3d


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多