c# - 如何访问保存在服务器和本地的文件?
问题描述
我正在 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;
}
解决方案
我从互联网上尝试了多种解决方案,最后找到了正确的方法来下载并使用以下代码保存文件:
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);
}
推荐阅读
- excel - Excel 公式以匹配日期范围内的项目
- javascript - JavaScript:使用 forEach 查看数组是否包含特定的数值
- kubernetes - 如何以编程方式从其中一个集群中获取当前的 GKE 项目 ID?
- kubernetes - 为每个命名空间定义值
- java - 用于业务逻辑和数据库连接的 Junit Spring Boot 单元测试
- hibernate - OptimisticLockException 使用 @Version 与 ConcurrentModificationException
- angular - 路由器的Angular 7动画只工作一次
- javascript - React - 如何保护仅适用于管理员用户的内容?
- node.js - 错误:ENOENT:没有这样的文件或目录,scandir '.../node_modules/node-sass/vendor'
- java - 在 Mac 上安装 Java 8:为什么我不能下载文件?它重定向到登录