using System.Collections.Generic; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; using System.IO; using System.Threading.Tasks; using Vit.Extensions; namespace Vit.Net.Http.FormFile { /* * https://www.cnblogs.com/liuxiaoji/p/10266609.html * */ public class FormFile { /// /// 文件在form中的name(如 "files") /// public string formKey; /// /// 上传文件时的文件名称(含后缀 如 "user.jpg") /// public string fileName; /// /// 文件的二进制正文内容 /// public byte[] content; } /// /// /// public class MultipartForm { public Dictionary form { get; private set; } public List files { get; private set; } public MultipartForm(Stream Body, string ContentType) { ReadMultipartForm(this, Body, ContentType); } public MultipartForm(byte[] Body, string ContentType) { using (var stream = new MemoryStream(Body)) { ReadMultipartForm(this, stream, ContentType); } } #region ReadMultipartForm private static async Task ReadMultipartForm(MultipartForm formData,Stream Body, string ContentType) { var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(ContentType).Boundary).Value; var reader = new MultipartReader(boundary, Body); formData.files = new List(); formData.form = new Dictionary(); MultipartSection section; while ((section = await reader.ReadNextSectionAsync()) != null) { ContentDispositionHeaderValue contentDisposition = section.GetContentDispositionHeader(); if (contentDisposition == null) continue; if (contentDisposition.IsFileDisposition()) { var file = section.AsFileSection(); byte[] buff = await section.Body.ToBytesAsync(); //byte[] buff = await file.FileStream.ToBytesAsync(); formData.files.Add(new FormFile { formKey = file.Name, fileName = contentDisposition.FileName.ToString(), content = buff }); } else if (contentDisposition.IsFormDisposition()) { var form = section.AsFormDataSection(); formData.form[form.Name] = await form.GetValueAsync(); } } return formData; } #endregion } }