MultipartUtil.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. namespace Alipay.EasySDK.Kernel.Util
  5. {
  6. /// <summary>
  7. /// HTTP multipart/form-data格式相关工具类
  8. /// </summary>
  9. public static class MultipartUtil
  10. {
  11. /// <summary>
  12. /// 获取Multipart分界符
  13. /// </summary>
  14. /// <param name="boundary">用作分界的随机字符串</param>
  15. /// <returns>Multipart分界符</returns>
  16. public static byte[] GetEntryBoundary(string boundary)
  17. {
  18. return Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
  19. }
  20. /// <summary>
  21. /// 获取Multipart结束标记
  22. /// </summary>
  23. /// <param name="boundary">用作分界的随机字符串</param>
  24. /// <returns>Multipart结束标记</returns>
  25. public static byte[] GetEndBoundary(string boundary)
  26. {
  27. return Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
  28. }
  29. /// <summary>
  30. /// 获取Multipart中的文本参数结构
  31. /// </summary>
  32. /// <param name="fieldName">字段名称</param>
  33. /// <param name="fieldValue">字段值</param>
  34. /// <returns>文本参数结构</returns>
  35. public static byte[] GetTextEntry(string fieldName, string fieldValue)
  36. {
  37. string entry = "Content-Disposition:form-data;name=\""
  38. + fieldName
  39. + "\"\r\nContent-Type:text/plain\r\n\r\n"
  40. + fieldValue;
  41. return AlipayConstants.DEFAULT_CHARSET.GetBytes(entry);
  42. }
  43. /// <summary>
  44. /// 获取Multipart中的文件参数结构(不含文件内容,只有文件元数据)
  45. /// </summary>
  46. /// <param name="fieldName">字段名称</param>
  47. /// <param name="filePath">文件路径</param>
  48. /// <returns>文件参数结构(不含文件内容)</returns>
  49. public static byte[] GetFileEntry(String fieldName, String filePath)
  50. {
  51. ArgumentValidator.CheckArgument(File.Exists(filePath),
  52. Path.GetFullPath(filePath) + "文件不存在");
  53. ArgumentValidator.CheckArgument(Path.GetFileName(filePath).Contains("."),
  54. "文件名必须带上正确的扩展名");
  55. String entry = "Content-Disposition:form-data;name=\""
  56. + fieldName
  57. + "\";filename=\""
  58. + Path.GetFileName(filePath)
  59. + "\"\r\nContent-Type:application/octet-stream"
  60. + "\r\n\r\n";
  61. return AlipayConstants.DEFAULT_CHARSET.GetBytes(entry);
  62. }
  63. /// <summary>
  64. /// 往指定流中写入整个字节数组
  65. /// </summary>
  66. /// <param name="stream">流</param>
  67. /// <param name="content">字节数组</param>
  68. public static void WriteToStream(Stream stream, byte[] content)
  69. {
  70. stream.Write(content, 0, content.Length);
  71. }
  72. }
  73. }