因为阿里云oss 不支持图片处理,又在一则广告上看到腾讯云50GB存储和50GB流量免费,万象优图也支持图片处理。于是就来研究了一番,不过万象优图没有在线管理,上传后都不知道传了哪些,所以需要自己做一个数据库来记录下了。
腾讯云上面有各种SDK 唯独没有 .net !! 这对.net程序员怎么能忍,好在我java也还行,就只好照着java sdk做了一个出来,还是废了不少功夫才成功.有一点request.GetResponse() 如果不成功,腾讯云返回的不是200,这里会抛异常,但我要知道它返回报错的json 吧,后来在国外一篇文章上看到可以在cath 里的WebException 里取。
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace WindowsFormsApplication1
{
/// <summary>
/// 腾讯云帮助类
/// </summary>
public class QCloudHelper
{
#region 私有方法
/// <summary>
/// DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static long ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000000;
return t;
}
/// <summary>
/// 对数据进行Hmac签名(仅适用于腾讯云)
/// </summary>
/// <param name="valueStr">要签名的数据</param>
/// <param name="keyStr">密钥</param>
/// <returns></returns>
private static string Sign(string valueStr, string keyStr)
{
HMAC hmac = HMACSHA1.Create();
//源数据
var data = System.Text.Encoding.UTF8.GetBytes(valueStr);
//密钥
var key = System.Text.Encoding.UTF8.GetBytes(keyStr);
//设置密钥
hmac.Key = key;
//计算哈希值
var hash = hmac.ComputeHash(data);
//对数据进行签名
var signedData = hash.Concat(data).ToArray();
var receivedHash = signedData.Take(hmac.HashSize >> 3).ToArray();
byte[] all = new byte[receivedHash.Length + data.Length];
Buffer.BlockCopy(receivedHash, 0, all, 0, receivedHash.Length);
Buffer.BlockCopy(data, 0, all, receivedHash.Length, data.Length);
String result = Convert.ToBase64String(all);
return result;
}
#endregion
/// <summary>
/// 上传图片到万象优图
/// </summary>
/// <param name="appid"></param>
/// <param name="bucket"></param>
/// <param name="fs"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static void UploadToWanxiang(string appid, string bucket, Stream fs, string fileName)
{
string url = "http://web.image.myqcloud.com/photos/v2/" + appid + "/" + bucket + "/0/";
//图片的Md5值,如果提供,服务会对上传的文件做Md5校验及秒传
List<byte> data = new List<byte>();
byte[] buffer = new byte[4096];
int read = fs.Read(buffer, 0, buffer.Length);
while (read > 0)
{
for (int i = 0; i < read; i++)
{
data.Add(buffer[i]);
}
read = fs.Read(buffer, 0, buffer.Length);
}
fs.Close();
var arr = data.ToArray();
MD5 algorithm = System.Security.Cryptography.MD5.Create();
string md5 = BitConverter.ToString(algorithm.ComputeHash(arr)).Replace("-", "");
string auth = AuthorizationMulti(appid, bucket, "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxx");
//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"filecontent\"; filename=\"");
sb.Append(fileName);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type:");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
// 根据uri创建HttpWebRequest对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
//对发送的数据不使用缓存
//request.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(300秒)
request.Timeout = 300000;
request.ContentType = "multipart/form-data; boundary=" + strBoundary;
//request.ContentLength = arr.Length+ postHeaderBytes.Length;
request.Host = "web.image.myqcloud.com";
//request.Headers.Set(HttpRequestHeader.Authorization, auth);
request.Headers.Add("Authorization", auth);
Stream postStream = request.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(arr, 0, arr.Length);
byte[] endData = Encoding.UTF8.GetBytes("\r\n--" + strBoundary + "--\r\n");
postStream.Write(endData, 0, endData.Length);
postStream.Close();
//获取服务器端的响应
try
{
using (WebResponse response = request.GetResponse())
{
// Success
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
}
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
}
}
}
//WebResponse webRespon = request.GetResponse();
//Stream s = webRespon.GetResponseStream();
//StreamReader sr = new StreamReader(s);
////读取服务器端返回的消息
//String sReturnString = sr.ReadToEnd();
//sr.Close();
//WebClient wc = new WebClient();
//wc.Headers.Add("Host", "web.image.myqcloud.com");
//wc.Headers.Add("Content-Length", arr.Length + "");
////时间戳
//string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
//wc.Headers.Add("Content-Type", "application/octet-stream" + strBoundary);
//wc.Headers.Add("Authorization", auth);
//wc.h
//wc.UploadDataAsync(new Uri(url), arr);
//wc.UploadDataCompleted += Wc_UploadDataCompleted;
}
private static void Wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
string result = Encoding.UTF8.GetString(e.Result);
}
//
//Secret Key: xxxxxxxxxxxxxxxxxxxxx
/// <summary>
/// 获取多次签名用于鉴权
/// </summary>
/// <param name="appid"></param>
/// <param name="bucket"></param>
/// <param name="secretID"></param>
/// <param name="SecretKey"></param>
/// <returns></returns>
public static string AuthorizationMulti(string appid, string bucket, string secretID, string SecretKey)
{
//多次
// string s = "a=[appid]&b=[bucket]&k=[SecretID]&e=[expiredTime]&t=[currentTime]&r=[rand]&u=[userid]&f=[fileid]";
string s = "a=" + appid + "&b=" + bucket + "&k=" + secretID + "&e=" + ConvertDateTimeInt(DateTime.Now.AddMonths(1)) + "&t=" + ConvertDateTimeInt(DateTime.Now) + "&r=" + Guid.NewGuid().ToString("N").Substring(0, 10) + "&u=0&f=";
string sign = Sign(s, SecretKey);
return sign;
}
/// <summary>
/// 获取单次签名用于鉴权
/// </summary>
/// <param name="appid"></param>
/// <param name="bucket"></param>
/// <param name="secretID"></param>
/// <param name="SecretKey"></param>
/// <returns></returns>
public string AuthorizationSingle(string appid, string bucket, string secretID, string SecretKey)
{
//单次
// string s = "a=[appid]&b=[bucket]&k=[SecretID]&e=[expiredTime]&t=[currentTime]&r=[rand]&u=[userid]&f=[fileid]";
string s = "a=" + appid + "&b=" + bucket + "&k=" + secretID + "&e=0&t=" + ConvertDateTimeInt(DateTime.Now) + "&r=" + Guid.NewGuid().ToString("N").Substring(0, 10) + "&u=&f=[fileid]";
string sign = Sign(s, SecretKey);
return sign;
}
}
}
珂珂的个人博客 - 一个程序猿的个人网站