首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将.txt文件从统一C#上传到防火墙存储

将.txt文件从统一C#上传到防火墙存储
EN

Stack Overflow用户
提问于 2021-10-22 09:00:30
回答 1查看 226关注 0票数 0

到目前为止,在互联网上进行了一些研究之后,我已经能够从计算机中选择.jpeg文件,并使用UnifiedC#将其上传到防火墙。

但是,我不知道应该如何修改下面的代码来使用它来上传.txt文件。

如果有其他更简单的方法来完成这个任务,请告诉我(如果有的话)。否则,告诉我如何修改这段代码,使其达到上述目的。

代码语言:javascript
复制
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!");
            }
        });


    }
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-22 14:22:39

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

我觉得你真正需要做的就是

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

使用正确的ContentType

所以也许就像

代码语言:javascript
复制
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 ;)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69674149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档