Minio上传文件

1.安装Minio Nuget包

Github地址,使用此仓库的release插件,在Unity中安装Nuget包。

注意:在VS工程中安装是不起作用的,必须在Unity中安装。

安装完成后,在Unity中打开管理器:

然后搜索Minio:

然后安装。

实测在PC和Android中都可以使用Minio。

2.脚本

using Minio;
using Minio.DataModel.Args;
using Minio.Exceptions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public static class MinioHelper
{
    private static string endPoint =  "";
    private static string accessKey = "";
    private static string secretKey = "";
    private static IMinioClient minio;

    static void InitMinio(bool https=true)
    {
        try
        {
            if (https)
            {
                minio = new MinioClient()
                                .WithEndpoint(endPoint)
                                .WithCredentials(accessKey, secretKey)
                                .WithSSL() //没有搭https的话,把连接语句的 WithSSL() 去掉即可
                                .Build();
            }
            else
            {
                minio = new MinioClient()
                    .WithEndpoint(endPoint)
                    .WithCredentials(accessKey, secretKey)
                    .Build();
            }

            Debug.Log("MinIO Init!");
        }
        catch (Exception ex)
        {
            Debug.LogError("初始化Minio失败!请检查参数是否正常!");
        }
    }

    public static void UploadFile(string filePath,string bucketName,string objectName="")
    {
        if (minio == null) InitMinio();
        if (string.IsNullOrEmpty(objectName)) objectName = Path.GetFileName(filePath);

        FileUpload(bucketName,objectName,filePath,UploadEvent).Wait();
    }

    static void UploadEvent(bool state)
    {
        Debug.Log("上传:"+state.ToString());
    }

    /// <summary>
    ///  文件上传
    /// </summary>
    private static async Task FileUpload(string bucketName,string objectName,string filePath,Action<bool> action)
    {
        try
        {
            // 在服务器上制作一个bucket(如果还没有)
            var beArgs = new BucketExistsArgs().WithBucket(bucketName);
            bool found = await minio.BucketExistsAsync(beArgs).ConfigureAwait(false);
            if (!found)
            {
                var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                await minio.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }
            // 将文件上传到bucket
            var putObjectArgs = new PutObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithFileName(filePath);
            await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);

            action.Invoke(true);
        }
        catch (MinioException e)
        {
            action.Invoke(false);
        }
    }
}