C#、asp.net阿里云(aliyun)OSS上传文件

首先引用阿里云开源Nuget包Aliyun.OSS.SDK

然后在OSS中配置使用OSS上传必要的配置,具体文档查看地址:https://help.aliyun.com/document_detail/31947.html?spm=a2c4g.11186623.6.1574.32fe34704pHexv

这些都已具备后,直接进行上传,代码示例如下:

 static string accessKeyId = ConfigurationManager.AppSettings["AccessKeyId"];
        static string accessKeySecret = ConfigurationManager.AppSettings["AccessKeySecret"];
        static string endpoint = ConfigurationManager.AppSettings["Endpoint"];
        static string bucketName_file = ConfigurationManager.AppSettings["Bucket_Picture"];//OSS图片存储空间

        static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

        /// <summary>
        /// 文件简单上传
        /// </summary>
        /// <param name="bucketName">存储空间</param>
        /// <param name="fileName">文件名(若要新建文件夹:文件夹名/文件名)</param>
        /// <param name="content">上传的文件</param>
        /// <returns></returns>
        public bool PutObjectFromFile(string bucketName, string fileName, Stream content)
        {
            try
            {
                bool result = false;
                var obj = client.PutObject(bucketName, fileName, content);
                if (obj != null && obj.HttpStatusCode == HttpStatusCode.OK)
                {
                    result = true;
                }
                return result;
            }
            catch (OssException ex)
            {
                WriteDataLog.WriteLog(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3},BucketName:{4},fileName:{5}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId, bucketName, fileName));
                return false;
            }
            catch (Exception ex)
            {
                WriteDataLog.WriteLog(string.Format("Failed with error info: {0},BucketName:{1},fileName:{2}", ex.Message, bucketName, fileName));
                return false;
            }
        }

相关代码其实比较少,但是配置相关的东西一定要配置对,否则会一直报错。

如果有什么不清楚的地方,欢迎留言探讨。

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值