首页 > 解决方案 > 从 Unity C# 将 .txt 文件上传到 Firebase 存储

问题描述

到目前为止,经过互联网的一些研究,我已经能够从计算机中选择 .jpeg 文件并使用 Unity C# 将其上传到 firebase。

但是,我无法弄清楚,我应该如何修改下面的代码以使用它来上传 .txt 文件。

如果有其他更简单的方法来完成这项任务,请告诉(如果有的话)。否则,请告诉我应该如何修改此代码以实现上述目的。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

//For Picking files
using System.IO;
using SimpleFileBrowser;

//For firebase storage
using Firebase;
using Firebase.Extensions;
using Firebase.Storage;
public class UploadFile : MonoBehaviour
{
FirebaseStorage storage;
StorageReference storageReference;
// Start is called before the first frame update
void Start()
{

    FileBrowser.SetFilters(true, new FileBrowser.Filter("Images", ".jpg", ".png"), new FileBrowser.Filter("Text Files", ".txt", ".pdf"));

    FileBrowser.SetDefaultFilter(".jpg");


    FileBrowser.SetExcludedExtensions(".lnk", ".tmp", ".zip", ".rar", ".exe");
    storage = FirebaseStorage.DefaultInstance;
    storageReference = storage.GetReferenceFromUrl("gs://app_name.appspot.com/");


}

public void OnButtonClick()
{
    StartCoroutine(ShowLoadDialogCoroutine());

}

IEnumerator ShowLoadDialogCoroutine()
{

    yield return FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load");

    Debug.Log(FileBrowser.Success);

    if (FileBrowser.Success)
    {
        // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
        for (int i = 0; i < FileBrowser.Result.Length; i++)
            Debug.Log(FileBrowser.Result[i]);

        Debug.Log("File Selected");
        byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);
        //Editing Metadata
        var newMetadata = new MetadataChange();
        newMetadata.ContentType = "image/jpeg";

        //Create a reference to where the file needs to be uploaded
        StorageReference uploadRef = storageReference.Child("uploads/newFile.jpeg");
        Debug.Log("File upload started");
        uploadRef.PutBytesAsync(bytes, newMetadata).ContinueWithOnMainThread((task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                Debug.Log("File Uploaded Successfully!");
            }
        });


    }
}

}

标签: c#unity3dfirebase-storage

解决方案


据我了解,它基本上已经按预期工作,但是您需要以不同的方式处理不同的文件类型/扩展名。

我认为你真正需要做的就是

  • 使用正确的文件名 + 扩展名
  • ContentType根据文件扩展名使用正确的

所以也许像

IEnumerator ShowLoadDialogCoroutine()
{
    yield return FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load");

    Debug.Log(FileBrowser.Success);

    if (!FileBrowser.Success)
    {
        yield break;
    }

    //foreach (var file in FileBrowser.Result)
    //{
    //    Debug.Log(file);
    //}

    var file = FileBrowser.Result[0];

    Debug.Log("File Selected: \"{file}\"");

    // e.g. C:\someFolder/someFile.txt => someFile.txt
    var fileNameWithExtension = file.Split('/', '\\').Last();

    if (!fileNameWithExtension.Contains('.'))
    {
        throw new ArgumentException($"Selected file \"{file}\" is not a supported file!");
    }

    // e.g. someFile.txt => txt
    var extensionWithoutDot = fileNameWithExtension.Split('.').Last();

    // Get MIME type according to file extension
    var contentType = extensionWithoutDot switch
    {
        "jpg" => $"image/jpeg",
        "jpeg" => $"image/jpeg",
        "png" => $"image/png",
        "txt" => "text/plain",
        "pdf" => "application/pdf",
        _ => throw new ArgumentException($"Selected file \"{file}\" of type \"{extensionWithoutDot}\" is not supported!")
    };

    // Use dynamic content / MIME type
    var newMetadata = new MetadataChange()
    {
        ContentType = contentType
    };

    // Use the actual selected file name including extension
    StorageReference uploadRef = storageReference.Child($"uploads/{fileNameWithExtension}");
    Debug.Log("File upload started");
    uploadRef.PutBytesAsync(bytes, newMetadata).ContinueWithOnMainThread((task) =>
    {
        if (task.IsFaulted || task.IsCanceled)
        {
            Debug.LogException(task.Exception);
        }
        else
        {
            Debug.Log($"File \"{file}\" Uploaded Successfully!");
        }
    });
}

您很可能希望throw稍后用用户反馈来替换正确的错误处理;)


推荐阅读