TG.WXCRM.V4/Common/AliyunHelper.cs

210 lines
7.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace WX.CRM.Common
{
public class AliyunHelper
{
#region
/// <summary>
/// 设置上传的文件的key值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string UploadImage(string path, string imgKey)
{
#region
//iLCVNfsiH4F1JLNU
//24DOemjGGeQeG2WJNzHBqi1wNtySgB
//http://qp-wechat-img.oss-cn-shenzhen.aliyuncs.com
//qp-wechat-img
string aliAccessKeyId = Utility.GetSettingByKey("AliAccessKeyId") ?? "iLCVNfsiH4F1JLNU";
string aliAccessKeySecret = Utility.GetSettingByKey("AliAccessKeySecret") ?? "24DOemjGGeQeG2WJNzHBqi1wNtySgB";
string aliBucketHost = Utility.GetSettingByKey("AliBucketHost") ?? "http://qp-wechat-img.oss-cn-shenzhen.aliyuncs.com";
string aliBucket = Utility.GetSettingByKey("AliBucket") ?? "qp-wechat-img";
#endregion
if (string.IsNullOrEmpty(aliAccessKeyId) || string.IsNullOrEmpty(aliAccessKeySecret) || string.IsNullOrEmpty(aliBucketHost) || string.IsNullOrEmpty(aliBucket))
{
throw new Exception("阿里oss配置错误");
}
var ossClient = new OssClient(aliBucketHost, aliAccessKeyId, aliAccessKeySecret);
try
{
var result = ossClient.PutObject(aliBucket, imgKey, path);
return aliBucketHost + "/" + imgKey;
}
catch (Exception es)
{
LogHelper.Error(string.Format("Put object failed, {0}", es.Message));
}
return null;
}
#endregion
public static string UploadImage(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new Exception("路径不能为空!");
}
try
{
var md5 = Utility.GetMD5HashFromFile(path);
return UploadImage(path, md5);
}
catch
{
throw;
}
}
}
public class AliHelper
{
private string AccessKeyId = ""; //密钥ID
private string AccessKeySecret = "";
private string Format = "JSON"; //返回值的类型
private string Version = ""; //API版本号
private string Signature = ""; //签名结果串
private string SignatureMethod = "HMAC-SHA1"; //签名方式目前支持HMAC-SHA1
private string Timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); //请求的时间戳 日期格式按照ISO8601标准表示并需要使用UTC时间 yyyy-MM-ddTHH:mm:ssZ;
private string SignatureVersion = "1.0"; //签名算法版本
private string SignatureNonce = Guid.NewGuid().ToString(); //唯一随机数,用于防止网络重放攻击。用户在不同请求间要使用不同的随机数值
public AliHelper(string AccessKeyId, string AccessKeySecret, string Version)
{
this.AccessKeyId = AccessKeyId;
this.AccessKeySecret = AccessKeySecret;
this.Version = Version;
}
/// <summary>
/// 计算签名
/// </summary>
///
private void ComputeSignature(Dictionary<string, object> ditParam, string method = "GET")
{
BuildParameters(ditParam);
//按ascii码排序
Dictionary<string, object> asciiDit = new Dictionary<string, object>();
string[] KeyArr = ditParam.Keys.ToArray();
Array.Sort(KeyArr, string.CompareOrdinal);
foreach (var key in KeyArr)
{
string value = ditParam[key].ToString();
asciiDit.Add(key, value);
}
//计算签名
var canonicalizedQueryString = string.Join("&",
asciiDit.Select(x => PercentEncode(x.Key) + "=" + PercentEncode(x.Value.ToString())));
var stringToSign = method.ToString().ToUpper() + "&" + PercentEncode("/") + "&" + PercentEncode(canonicalizedQueryString);
var keyBytes = Encoding.UTF8.GetBytes(AccessKeySecret + "&");
var hmac = new HMACSHA1(keyBytes);
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
Signature = Convert.ToBase64String(hashBytes);
ditParam.Add("Signature", Signature);
}
//获取公共参数和相关方法中的参数
private void BuildParameters(Dictionary<string, object> ditParam)
{
ditParam.Add("Format", Format.ToUpper());
ditParam.Add("Version", Version);
ditParam.Add("AccessKeyId", AccessKeyId);
ditParam.Add("Timestamp", Timestamp);
ditParam.Add("SignatureMethod", SignatureMethod);
ditParam.Add("SignatureVersion", SignatureVersion);
ditParam.Add("SignatureNonce", SignatureNonce);
}
private string PercentEncode(string value)
{
return UpperCaseUrlEncode(value)
.Replace("/", "%2F")
.Replace("+", "%20")
.Replace("*", "%2A")
.Replace("%7E", "~")
.Replace("!", "%21")
.Replace("'", "%27")
.Replace("(", "%28")
.Replace(")", "%29");
}
private string UpperCaseUrlEncode(string s)
{
// C# 的 HttpUtility.UrlEncode() 编码得到的形如 %xx%xx的内容是小写的Java 的是大写的。
char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
for (int i = 0; i < temp.Length - 2; i++)
{
if (temp[i] == '%')
{
temp[i + 1] = char.ToUpper(temp[i + 1]);
temp[i + 2] = char.ToUpper(temp[i + 2]);
}
}
return new string(temp);
}
public string HttpGetUrl(string Url, Dictionary<string, object> ditParam)
{
ComputeSignature(ditParam);
var param = string.Join("&", ditParam.Select(x => x.Key + "=" + HttpUtility.UrlEncode(x.Value.ToString())));
var u = Url + (param == "" ? "" : "?") + param;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(u);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
}
public class Credentials
{
public string SecurityToken { get; set; }
public string AccessKeyId { get; set; }
public string AccessKeySecret { get; set; }
public string Expiration { get; set; }
}
}