阿里云 OSS 文件管理

OSS 文件上传

AliyunOSSHelper 类

 public class AliyunOSSHelper
    {
      //  private static string endpoint = ConfigurationManager.AppSettings["AliyunOSS_endpoint"] ?? "";
      //  private static string accessKeyId = ConfigurationManager.AppSettings["AliyunOSS_accessKeyId"] ?? "";
      //  private static string accessKeySecret = ConfigurationManager.AppSettings["AliyunOSS_accessKeySecret"] ?? "";
       // private static string remoteKey = ConfigurationManager.AppSettings["AliyunOSS_Path"] ?? "";

         private static string endpoint = "http://oss-ap-southeast-1.aliyuncs.com";
        private static string accessKeyId = "accessKeyId";
        private static string accessKeySecret = "accessKeySecret";
        private static string remoteKey = "Inventory_Files/";


   //判断 文件是否存在OSS上
  public static bool DoesObject(string bucketName, string filepath)
        {
            bool result = false;
            var _configuration = new ClientConfiguration();
            _configuration.ConnectionTimeout = 20000;
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                var exist = client.DoesObjectExist(bucketName, filepath);
                //if (!exist)
                //{
                //    client.PutObject(bucketName, filepath, filePathToUpload);
                //}
                //  result = exist;
                return exist;
            }
            catch (OssException ex)
            {
                result = false;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }




    public static bool CreateBucket(string bucketName)
    {
        var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        try
        {
            var bucket = client.CreateBucket(bucketName);
            if (bucket != null)
                return true;

            return false;
        }
        catch (OssException ex)
        {
            Trace.WriteLine(string.Format(
                "CreateBucket Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
            return false;
        }
    }

	//上传文件
    public static bool PutObject(string bucketName, string filepath, string filePathToUpload)
    {
        bool result = false;
        var _configuration = new ClientConfiguration();
        _configuration.ConnectionTimeout = 20000;
        var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        try
        {
            var exist = client.DoesObjectExist(bucketName, filepath);
            if (!exist)
            {
                client.PutObject(bucketName, filepath, filePathToUpload);
            }
            result = true;
        }
        catch (OssException ex)
        {
            Trace.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
        }
        catch (Exception ex)
        {
            Trace.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
        }
        return result;
    }

	//获取文件夹下存储的文件 列表
    public static List<string> ListObjects(string bucketName, string prefix)
    {
        List<string> fileList = new List<string>();
        var _configuration = new ClientConfiguration();
        _configuration.ConnectionTimeout = 20000;
        var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        try
        {
            ObjectListing result = null;
            string nextMarker = string.Empty;
            do
            {
                // 每页列举的文件个数通过maxKeys指定,超过指定数将进行分页显示。
                var listObjectsRequest = new ListObjectsRequest(bucketName)
                {
                    Prefix = prefix,
                    Marker = nextMarker,
                    MaxKeys = 100
                };
                result = client.ListObjects(listObjectsRequest);
                foreach (var summary in result.ObjectSummaries)
                {
                    fileList.Add(summary.Key);
                    //Console.WriteLine("Name:{0}", summary.Key);
                }
                nextMarker = result.NextMarker;
            } while (result.IsTruncated);
        }
        catch (OssException ex)
        {
            Trace.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
        }
        catch (Exception ex)
        {
            Trace.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
        }
        return fileList;
    }

    #region Inventory 删除
    /// <summary>
    /// Inventory 删除近30天内的数据
    /// </summary>
    /// <param name="fileType"></param>
    public static void DeleteObjects(string fileType)
    {
        try
        {
            string bucketname = (fileType == "PDA" ? "pdafile" : "ftpserverfile");
            List<string> fileList = Inventory_ListObjects(bucketname, remoteKey);

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var request = new DeleteObjectsRequest(bucketname, fileList, false);
            client.DeleteObjects(request);

            Trace.WriteLine(string.Format("Delete File {0}", request.Keys.Count));

        }
        catch (OssException ex)
        {
            Trace.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
             ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
        }
        catch (Exception ex)
        {
            Trace.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
        }
    }

    /// <summary>
    /// 查询集合列表
    /// </summary>
    public static List<string> Inventory_ListObjects(string bucketName, string prefix)
    {
        List<string> fileList = new List<string>();
        var _configuration = new ClientConfiguration();
        _configuration.ConnectionTimeout = 20000;
        var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        try
        {
            ObjectListing result = null;
            string nextMarker = string.Empty;
            do
            {
                // 每页列举的文件个数通过maxKeys指定,超过指定数将进行分页显示。
                var listObjectsRequest = new ListObjectsRequest(bucketName)
                {
                    Prefix = prefix,
                    Marker = nextMarker,
                    MaxKeys = 100
                };
                result = client.ListObjects(listObjectsRequest);

                //获取近一个月的数据上次传
                DateTime strtime = DateTime.Now.AddDays(1).Date;
                DateTime endtime = strtime.AddDays(-30).Date;

                foreach (var summary in result.ObjectSummaries)
                {
                    if (summary.LastModified >= endtime && summary.LastModified < strtime)
                    {
                        fileList.Add(summary.Key);
                    }
               
                    //Console.WriteLine("Name:{0}", summary.Key);
                }


                nextMarker = result.NextMarker;
            } while (result.IsTruncated);
        }
        catch (OssException ex)
        {
            Trace.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
        }
        catch (Exception ex)
        {
            Trace.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
        }
        return fileList;
    }
    #endregion


}

调用

  #region Inventory 导出

    public ActionResult ExcelPrint(string FileName)
    {
        if (string.IsNullOrEmpty(FileName))
        {
            return Json(new { IsSuccess = false, Msg = "File does not exist." });
        }

        string FileFullPath = Server.MapPath(FileName);
        if (!System.IO.File.Exists(FileFullPath))
        {
            //没有 从 阿里云获取
            string pathaddress = FileName.Replace("/Upload/Reports/Inventory_Files//", "");
            FileFullPath = "https://ftpserverfile.oss-ap-southeast-1.aliyuncs.com/Inventory_Files/" + pathaddress;



            //Inventory_Files/BAY/20210113/Bangkok/20210113112215/รายงานเงินสดคงคลัง GFCTH หลักสี่ 13-01-2021 (Basic).xls
            string filepath = "Inventory_Files/" + pathaddress;
            bool IsExistence = AliyunOSSHelper.DoesObject("ftpserverfile", filepath);
            if (IsExistence)
            {
                //存在
                return Json(new { IsSuccess = true, Msg = FileFullPath });
            }
            else
            {
                //不存在
                return Json(new { IsSuccess = false, Msg = "File does not exist." });
            }

        
        }
        else
        {
            return Json(new { IsSuccess = true, Msg = FileName });
        }
    }

    #endregion

#也可查阅 阿里云官方文档
https://helpcdn.aliyun.com/document_detail/91093.html?spm=a2c4g.11186623.6.1257.2a4e2da16ePzVA

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值