查看: 567|回复: 0

[.NET开发] 微信小程序基于腾讯云对象存储的图片上传

发表于 2018-4-24 08:00:01

在使用腾讯云对象存储之前,公司一直使用的是传统的FTP的上传模式,而随着用户量的不断增加,FTP所暴露出来的问题也越来越多,1.传输效率低,上传速度慢。2.时常有上传其他文件来攻击服务器,安全上得不到保障。所以我们在经过慎重考虑觉得使用第三方的云存储服务。

在最开始的时候我们在腾讯云与阿里云中选择,最终我们选择腾讯云,腾讯云在文件上传用时方面的性能比较突出,文件越大表现越好;在下载用时方面表现略优于阿里云;文件删除用时方面总体速度略逊于,但在不同大小文件删除用时上都比较稳定。当然这与我们主要用于开发微信小程序是有着密切的关系。

在我们酷客多小程序使用腾讯云对象存储的时候除了直接使用 API 接口外,COS 提供了丰富多样的 SDK 给我们使用,可是在他提供的SDK中并没有发现我们asp.net相关的SDK

在一番百度和一顿操作终于让我找到啦!看到没,只能说隐藏的真深,而且还是历史版本的,但是不管怎么样我们还是找到啦

找到C#的SDK,下载下来 (附上C#版本SDK的下载地址 C# SDK github项目下载地址)然后按照SDK中提供的方法,就可以成功上传!

然而并没有这么简单,当我们使用SDK中的方法的时候发现,SDK中的方法只适用于,绝对路径地址的文件上传!也就是并不满足我们ASP.Net中使用文件域上传文件。此时我们只有对方法进行改造!

附上改造过后代码:

  1. /// <summary>
  2. /// 文件流上传
  3. /// 说明: 酷客多小程序
  4. /// 其中分片上传使用SliceUploadInit SliceUploadData SliceUploadFinihs
  5. /// </summary>
  6. /// <param name="bucketName">bucket名称</param>
  7. /// <param name="remotePath">远程文件路径</param>
  8. /// <param name="localPath">本地文件路径</param>
  9. /// <param name="parameterDic">参数Dictionary</param>
  10. /// <returns></returns>
  11. public string UploadFile(string bucketName, string remotePath, Stream file, string filename,Dictionary<string, string> parameterDic = null)
  12. {
  13. if (remotePath.EndsWith("/"))
  14. {
  15. return constructResult(ERRORCode.ERROR_CODE_PARAMETER_ERROE, "file path can not end with '/'");
  16. }
  17. string bizAttribute = "";
  18. if (parameterDic != null && parameterDic.ContainsKey(CosParameters.PARA_BIZ_ATTR))
  19. bizAttribute = parameterDic[CosParameters.PARA_BIZ_ATTR];
  20. int insertOnly = 1;
  21. if (parameterDic != null && parameterDic.ContainsKey(CosParameters.PARA_INSERT_ONLY))
  22. {
  23. try
  24. {
  25. insertOnly = Int32.Parse(parameterDic[CosParameters.PARA_INSERT_ONLY]);
  26. }
  27. catch (Exception e)
  28. {
  29. Console.WriteLine(e.Message);
  30. return constructResult(ERRORCode.ERROR_CODE_PARAMETER_ERROE, "parameter insertOnly value invalidate");
  31. }
  32. }
  33. return Upload(bucketName, remotePath, file, filename, bizAttribute, insertOnly);
  34. }
复制代码
  1. /// <summary>
  2. /// 单个文件上传
  3. /// 说明: 酷客多小程序
  4. /// <param name="bucketName">bucket名称</param>
  5. /// <param name="remotePath">远程文件路径</param>
  6. /// <param name="localPath">本地文件路径</param>
  7. /// <param name="biz_attr">biz_attr属性</param>
  8. /// <param name="insertOnly">同名文件是否覆盖</param>
  9. /// <returns></returns>
  10. public string Upload(string bucketName, string remotePath, Stream file,string filename,
  11. string bizAttribute = "", int insertOnly = 1)
  12. {
  13. var url = generateURL(bucketName, remotePath);
  14. var sha1 = SHA1.GetFileSHA1(file);
  15. var data = new Dictionary<string, object>();
  16. data.Add("op", "upload");
  17. data.Add("sha", sha1);
  18. data.Add("biz_attr", bizAttribute);
  19. data.Add("insertOnly", insertOnly);
  20. var expired = getExpiredTime();
  21. var sign = Sign.Signature(appId, secretId, secretKey, expired, bucketName);
  22. var header = new Dictionary<string, string>();
  23. header.Add("Authorization", sign);
  24. return httpRequest.SendRequest(url, ref data, HttpMethod.Post, ref header, timeOut, file, filename);
  25. }
复制代码

  1. #region 直接上传文件流
  2. public string SendRequest(string url, ref Dictionary<string, object> data, HttpMethod requestMethod,
  3. ref Dictionary<string, string> header, int timeOut, Stream file,string filename, long offset = -1, int sliceSize = 0)
  4. {
  5. try
  6. {
  7. //Console.WriteLine("url:" + url);
  8. System.Net.ServicePointManager.Expect100Continue = false;
  9. if (requestMethod == HttpMethod.Get)
  10. {
  11. var paramStr = "";
  12. foreach (var key in data.Keys)
  13. {
  14. paramStr += string.Format("{0}=小贝&", key, HttpUtility.UrlEncode(data[key].ToString()));
  15. }
  16. paramStr = paramStr.TrimEnd('&');
  17. url += (url.EndsWith("?") ? "&" : "?") + paramStr;
  18. }
  19. request = (HttpWebRequest)HttpWebRequest.Create(url);
  20. request.Accept = CosDefaultValue.ACCEPT;
  21. request.KeepAlive = true;
  22. request.UserAgent = CosDefaultValue.USER_AGENT_VERSION;
  23. request.Timeout = timeOut;
  24. foreach (var key in header.Keys)
  25. {
  26. if (key == "Content-Type")
  27. {
  28. request.ContentType = header[key];
  29. }
  30. else
  31. {
  32. request.Headers.Add(key, header[key]);
  33. }
  34. }
  35. if (requestMethod == HttpMethod.Post)
  36. {
  37. request.Method = requestMethod.ToString().ToUpper();
  38. var memStream = new MemoryStream();
  39. if (header.ContainsKey("Content-Type") && header["Content-Type"] == "application/json")
  40. {
  41. var json = JsonConvert.SerializeObject(data);
  42. var jsonByte = Encoding.GetEncoding("utf-8").GetBytes(json.ToString());
  43. memStream.Write(jsonByte, 0, jsonByte.Length);
  44. }
  45. else
  46. {
  47. var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
  48. var beginBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  49. var endBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  50. request.ContentType = "multipart/form-data; boundary=" + boundary;
  51. var strBuf = new StringBuilder();
  52. foreach (var key in data.Keys)
  53. {
  54. strBuf.Append("\r\n--" + boundary + "\r\n");
  55. strBuf.Append("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n");
  56. strBuf.Append(data[key].ToString());
  57. }
  58. var paramsByte = Encoding.GetEncoding("utf-8").GetBytes(strBuf.ToString());
  59. memStream.Write(paramsByte, 0, paramsByte.Length);
  60. memStream.Write(beginBoundary, 0, beginBoundary.Length);
  61. var fileStream = file;
  62. const string filePartHeader =
  63. "Content-Disposition: form-data; name=\"fileContent\"; filename=\"{0}\"\r\n" +
  64. "Content-Type: application/octet-stream\r\n\r\n";
  65. var headerText = string.Format(filePartHeader, filename);
  66. var headerbytes = Encoding.UTF8.GetBytes(headerText);
  67. memStream.Write(headerbytes, 0, headerbytes.Length);
  68. if (offset == -1)
  69. {
  70. var buffer = new byte[1024];
  71. int bytesRead;
  72. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  73. {
  74. memStream.Write(buffer, 0, bytesRead);
  75. }
  76. }
  77. else
  78. {
  79. var buffer = new byte[sliceSize];
  80. int bytesRead;
  81. fileStream.Seek(offset, SeekOrigin.Begin);
  82. bytesRead = fileStream.Read(buffer, 0, buffer.Length);
  83. memStream.Write(buffer, 0, bytesRead);
  84. }
  85. fileStream.Close();
  86. memStream.Write(endBoundary, 0, endBoundary.Length);
  87. }
  88. request.ContentLength = memStream.Length;
  89. var requestStream = request.GetRequestStream();
  90. memStream.Position = 0;
  91. var tempBuffer = new byte[memStream.Length];
  92. memStream.Read(tempBuffer, 0, tempBuffer.Length);
  93. memStream.Close();
  94. requestStream.Write(tempBuffer, 0, tempBuffer.Length);
  95. requestStream.Close();
  96. //Console.WriteLine(strBuf.ToString());
  97. }
  98. //Console.WriteLine(request.ContentType.ToString());
  99. var response = request.GetResponse();
  100. using (var s = response.GetResponseStream())
  101. {
  102. var reader = new StreamReader(s, Encoding.UTF8);
  103. return reader.ReadToEnd();
  104. }
  105. }
  106. catch (WebException we)
  107. {
  108. if (we.Status == WebExceptionStatus.ProtocolError)
  109. {
  110. using (var s = we.Response.GetResponseStream())
  111. {
  112. var reader = new StreamReader(s, Encoding.UTF8);
  113. return reader.ReadToEnd();
  114. }
  115. }
  116. else
  117. {
  118. throw we;
  119. }
  120. }
  121. catch (Exception e)
  122. {
  123. throw e;
  124. }
  125. }
复制代码

使用上面改造过后的方法直接传入文件流即可通过文本域的方式上传文件到腾讯云上面去!

Asp.net 腾讯云对象存储的相关使用就介绍到这里,下次我们将介绍如何使用腾讯云对象存储打造图片管理模块。

-----酷客多小程序 刘崇杰



回复

使用道具 举报