MultipartForm.cs 3.0 KB

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