CSFramework.WebApi框架实现阿里云OSS上传、下载、删除文件功能
CSFramework.WebApi框架实现阿里云OSS上传、下载、删除文件功能
2. 重写命令层的Execute方法
3. 实现三个具体的操作。
流对象内容转字节:
阿里OSS在CSFramework.WebApi开发框架应用
APP项目有个新需求,用户提交的认证图片要存储到阿里OSS(阿里云对象存储服务),原来的接口是存储到APP服务器的。存储在OSS的图片可以通过OSS的域名管理将用户自己的域名绑定到 OSS 域名上,并支持 CDN 一键加速,这样可以直接通过域名访问OSS图片,比如:www.您的域名.com/ossimage/key.png,key对应OSS.key,唯一的文件名。
实现步骤:
1. 创建Cmd_AliOSSDemo命令层,继承CmdBaseAction命令层基类。
C# Code:
[CommandAttribute(811001, "阿里对象存储服务(OSS)上传、下载、删除文件")]
public class Cmd_AliOSSDemo : CmdBaseAction
{
private ModelAliOSS_Config _OssConfig;
private OssClient _OssClient;
public override object ClientData { get { return null; } }
public Cmd_AliOSSDemo(HttpRequestMessage httpRequest, IUserRequestAction userRequest)
: base(httpRequest, userRequest)
{
_Operations.Add("Get");//获取图片,返回图片URL数组
_Operations.Add("Put");//上传图片,每次上传1张图片
_Operations.Add("Del");//删除图片,每次删除1张图片
//阿里OSS配置
_OssConfig = new ModelAliOSS_Config
{
Bucket = "MyBucket",
Endpoint = "oss-cn-shenzhen.aliyuncs.com",
Key = "zLTAI6dmbcawzYpd= - 您的公钥",
KeySecret = "3qeQ7TqMEHIr9k1Apu76ljlLezxzB3 - 您的私钥"
};
_OssClient = new OssClient(_OssConfig.Endpoint, _OssConfig.Key, _OssConfig.KeySecret);
}
//
//省略代码....
//
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
public class Cmd_AliOSSDemo : CmdBaseAction
{
private ModelAliOSS_Config _OssConfig;
private OssClient _OssClient;
public override object ClientData { get { return null; } }
public Cmd_AliOSSDemo(HttpRequestMessage httpRequest, IUserRequestAction userRequest)
: base(httpRequest, userRequest)
{
_Operations.Add("Get");//获取图片,返回图片URL数组
_Operations.Add("Put");//上传图片,每次上传1张图片
_Operations.Add("Del");//删除图片,每次删除1张图片
//阿里OSS配置
_OssConfig = new ModelAliOSS_Config
{
Bucket = "MyBucket",
Endpoint = "oss-cn-shenzhen.aliyuncs.com",
Key = "zLTAI6dmbcawzYpd= - 您的公钥",
KeySecret = "3qeQ7TqMEHIr9k1Apu76ljlLezxzB3 - 您的私钥"
};
_OssClient = new OssClient(_OssConfig.Endpoint, _OssConfig.Key, _OssConfig.KeySecret);
}
//
//省略代码....
//
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
C# Code:
public override IUserResponse Execute()
{
#region 上传文件
if (this.EqualsOP(_UserRequest.Operation, "Put"))
{
ModelAliOSS_Put model = GetRequestData<ModelAliOSS_Put>(_UserRequest);
return Put(model);
}
#endregion
#region 获取文件
if (this.EqualsOP(_UserRequest.Operation, "Get"))
{
return Get(_UserRequest.Data);
}
#endregion
#region 删除文件
if (this.EqualsOP(_UserRequest.Operation, "Del"))
{
return Del(_UserRequest.Data);
}
#endregion
return new ModelResponse()
{
Message = ErrorCodes.UnknowOperation_Msg,
Code = ErrorCodes.UnknowOperation
};
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
{
#region 上传文件
if (this.EqualsOP(_UserRequest.Operation, "Put"))
{
ModelAliOSS_Put model = GetRequestData<ModelAliOSS_Put>(_UserRequest);
return Put(model);
}
#endregion
#region 获取文件
if (this.EqualsOP(_UserRequest.Operation, "Get"))
{
return Get(_UserRequest.Data);
}
#endregion
#region 删除文件
if (this.EqualsOP(_UserRequest.Operation, "Del"))
{
return Del(_UserRequest.Data);
}
#endregion
return new ModelResponse()
{
Message = ErrorCodes.UnknowOperation_Msg,
Code = ErrorCodes.UnknowOperation
};
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
3. 实现三个具体的操作。
Put:上传文件
Del:删除文件
Get:下载文件
接口请求参数模型:
C# Code:
internal IUserResponse Put(ModelAliOSS_Put model)
{
//获取根目录
string root = WebApiFileTool.GetRootPath(this.GetType().Assembly);
root = Path.Combine(root, "osstmp");
//创建临时目录,用于保存临时文件
if (!Directory.Exists(root)) Directory.CreateDirectory(root);
string fileName = Path.Combine(root, model.FileNameGUID);
if (SaveFileFromBase64String(model.FileBase64, fileName))
{
try
{
//开始上传文件
PutObjectResult result = _OssClient.PutObject(_OssConfig.Bucket, model.FileNameGUID, fileName);
return new ModelResponse { Code = 0, Data = result.ETag, Message = "上传文件成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
finally
{
if (File.Exists(fileName)) File.Delete(fileName);
}
}
else
{
return new ModelResponse { Code = -1, Data = "", Message = "Base64String转换OSS文件失败!" };
}
}
internal IUserResponse Get(string key)
{
try
{
var obj = _OssClient.GetObject(_OssConfig.Bucket, key);
byte[] bs = StreamToBytes(obj.ResponseStream);
var base64 = Convert.ToBase64String(bs);
return new ModelResponse { Code = 0, Data = base64, Message = "操作成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
}
internal IUserResponse Del(string key)
{
try
{
_OssClient.DeleteObject(_OssConfig.Bucket, key);
return new ModelResponse { Code = 0, Data = "", Message = "删除文件操作成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
{
//获取根目录
string root = WebApiFileTool.GetRootPath(this.GetType().Assembly);
root = Path.Combine(root, "osstmp");
//创建临时目录,用于保存临时文件
if (!Directory.Exists(root)) Directory.CreateDirectory(root);
string fileName = Path.Combine(root, model.FileNameGUID);
if (SaveFileFromBase64String(model.FileBase64, fileName))
{
try
{
//开始上传文件
PutObjectResult result = _OssClient.PutObject(_OssConfig.Bucket, model.FileNameGUID, fileName);
return new ModelResponse { Code = 0, Data = result.ETag, Message = "上传文件成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
finally
{
if (File.Exists(fileName)) File.Delete(fileName);
}
}
else
{
return new ModelResponse { Code = -1, Data = "", Message = "Base64String转换OSS文件失败!" };
}
}
internal IUserResponse Get(string key)
{
try
{
var obj = _OssClient.GetObject(_OssConfig.Bucket, key);
byte[] bs = StreamToBytes(obj.ResponseStream);
var base64 = Convert.ToBase64String(bs);
return new ModelResponse { Code = 0, Data = base64, Message = "操作成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
}
internal IUserResponse Del(string key)
{
try
{
_OssClient.DeleteObject(_OssConfig.Bucket, key);
return new ModelResponse { Code = 0, Data = "", Message = "删除文件操作成功" };
}
catch (Exception ex)
{
return new ModelResponse { Code = -1, Data = "", Message = ex.Message };
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
C# Code:
/// <summary>
/// 上传文件模型
/// </summary>
public class ModelAliOSS_Put
{
/// <summary>
/// 对应vw_Ali_OSS_Type,如:电子回单 = 20
/// </summary>
public string OSS_Type { get; set; }
/// <summary>
/// 文件类型,对应vw_Ali_OSS_ItemType,如: 营业执照 = 5,
/// </summary>
public string OSS_ItemType { get; set; }
/// <summary>
/// 关联单据号码, 货源单号或者托运单号,如运输单号,如:YD0102384111001
/// </summary>
public string RefDocNo { get; set; }
/// <summary>
/// 文件内容,Base64String
/// </summary>
public string FileBase64 { get; set; }
/// <summary>
/// 文件名,GUID32位全局唯一,如:409B018C-7525-4234-AAD9-5CB9508D293C.jpg
/// </summary>
public string FileNameGUID { get; set; }
/// <summary>
/// 文件描述
/// </summary>
public string FileDesc { get; set; }
/// <summary>
/// 上传用户编号或手机号
/// </summary>
public string UploadUser { get; set; }
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
/// 上传文件模型
/// </summary>
public class ModelAliOSS_Put
{
/// <summary>
/// 对应vw_Ali_OSS_Type,如:电子回单 = 20
/// </summary>
public string OSS_Type { get; set; }
/// <summary>
/// 文件类型,对应vw_Ali_OSS_ItemType,如: 营业执照 = 5,
/// </summary>
public string OSS_ItemType { get; set; }
/// <summary>
/// 关联单据号码, 货源单号或者托运单号,如运输单号,如:YD0102384111001
/// </summary>
public string RefDocNo { get; set; }
/// <summary>
/// 文件内容,Base64String
/// </summary>
public string FileBase64 { get; set; }
/// <summary>
/// 文件名,GUID32位全局唯一,如:409B018C-7525-4234-AAD9-5CB9508D293C.jpg
/// </summary>
public string FileNameGUID { get; set; }
/// <summary>
/// 文件描述
/// </summary>
public string FileDesc { get; set; }
/// <summary>
/// 上传用户编号或手机号
/// </summary>
public string UploadUser { get; set; }
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
阿里OSS接口的参数模型:
C# Code:
/// <summary>
/// 阿里云提供的OSS配置
/// </summary>
public class ModelAliOSS_Config
{
public string Bucket { get; set; }
public string Endpoint { get; set; }
public string Key { get; set; }
public string KeySecret { get; set; }
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
/// 阿里云提供的OSS配置
/// </summary>
public class ModelAliOSS_Config
{
public string Bucket { get; set; }
public string Endpoint { get; set; }
public string Key { get; set; }
public string KeySecret { get; set; }
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
base64String转文件:
C# Code:
/// <summary>
/// base64String转文件
/// </summary>
/// <param name="base64String">文件内容</param>
/// <param name="saveFileName">文件名</param>
/// <returns></returns>
private bool SaveFileFromBase64String(string base64String, string saveFileName)
{
try
{
var contents = Convert.FromBase64String(base64String);
using (var fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(contents, 0, contents.Length);
fs.Flush();
}
return File.Exists(saveFileName);
}
catch
{
return false;
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
/// base64String转文件
/// </summary>
/// <param name="base64String">文件内容</param>
/// <param name="saveFileName">文件名</param>
/// <returns></returns>
private bool SaveFileFromBase64String(string base64String, string saveFileName)
{
try
{
var contents = Convert.FromBase64String(base64String);
using (var fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(contents, 0, contents.Length);
fs.Flush();
}
return File.Exists(saveFileName);
}
catch
{
return false;
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
流对象内容转字节:
C# Code:
/// <summary>
/// 流对象内容转字节
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
/// 流对象内容转字节
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
扫一扫加微信:
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网