添加引用:Aliyun.OSS.SDK

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace YFAPICommon.Libs
{
    public class AliOSSTool
    {
        private const String accessKeyId = "xxxxxxxxx";
        private const String accessKeySecret = "xxxxxxxxxxxx";                                                                     
        private const string endpoint = "oss-cn-beijing.aliyuncs.com";
        private const string bucketName = "xxxxxxxxx";
        private const string serverUrl = "https://shuziyucai.oss-cn-beijing.aliyuncs.com/";
        public static string uploadFile(string objName,Stream sm,out string errormsg)
        {
            errormsg = null;
            // 创建OssClient实例。 
            var client = new Aliyun.OSS.OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                // 上传文件。 
                var result = client.PutObject(bucketName, objName, sm);
                if (result.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    return serverUrl + objName;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                errormsg = ex.Message;
            }
            finally
            {
                sm.Close();
            }
            return null;
        }

        public static string uploadFile(string objName, byte[] bts, out string errormsg)
        {
            Stream stream = new MemoryStream(bts);
            return uploadFile(objName,stream,out errormsg);
        }
    }
}

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐