MultipartForm.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using Microsoft.AspNetCore.WebUtilities;
  4. using Microsoft.Net.Http.Headers;
  5. using Vit.Extensions;
  6. namespace Vit.Net.Http.FormFile
  7. {
  8. /*
  9. * https://www.cnblogs.com/liuxiaoji/p/10266609.html
  10. *
  11. <ItemGroup>
  12. <PackageReference Include = "Microsoft.AspNetCore.Http" Version="2.2.2" />
  13. <PackageReference Include = "Microsoft.Net.Http.Headers" Version="2.2.8" />
  14. </ItemGroup>
  15. */
  16. public class FormFile
  17. {
  18. /// <summary>
  19. /// 文件在form中的name(如 "files")
  20. /// </summary>
  21. public string formKey;
  22. /// <summary>
  23. /// 上传文件时的文件名称(含后缀 如 "user.jpg")
  24. /// </summary>
  25. public string fileName;
  26. /// <summary>
  27. /// 文件的二进制正文内容
  28. /// </summary>
  29. public byte[] content;
  30. }
  31. /// <summary>
  32. ///
  33. /// </summary>
  34. public class MultipartForm
  35. {
  36. public Dictionary<string, string> form { get; private set; }
  37. public List<FormFile> files { get; private set; }
  38. public MultipartForm(Stream Body, string ContentType)
  39. {
  40. ReadMultipartForm(this, Body, ContentType);
  41. }
  42. public MultipartForm(byte[] Body, string ContentType)
  43. {
  44. using var stream = new MemoryStream(Body);
  45. ReadMultipartForm(this, stream, ContentType);
  46. }
  47. #region ReadMultipartForm
  48. private static MultipartForm ReadMultipartForm(MultipartForm formData, Stream Body, string ContentType)
  49. {
  50. var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(ContentType).Boundary).Value;
  51. var reader = new MultipartReader(boundary, Body);
  52. formData.files = new List<FormFile>();
  53. formData.form = new Dictionary<string, string>();
  54. MultipartSection section;
  55. while ((section = reader.ReadNextSectionAsync().Result) != null)
  56. {
  57. ContentDispositionHeaderValue contentDisposition = section.GetContentDispositionHeader();
  58. if (contentDisposition == null) continue;
  59. if (contentDisposition.IsFileDisposition())
  60. {
  61. var file = section.AsFileSection();
  62. byte[] buff = section.Body.ToBytes();
  63. //byte[] buff = await file.FileStream.ToBytesAsync();
  64. formData.files.Add(new FormFile { formKey = file.Name, fileName = contentDisposition.FileName.ToString(), content = buff });
  65. }
  66. else if (contentDisposition.IsFormDisposition())
  67. {
  68. var form = section.AsFormDataSection();
  69. formData.form[form.Name] = form.GetValueAsync().Result;
  70. }
  71. }
  72. return formData;
  73. }
  74. #endregion
  75. }
  76. }