.net 如何在webapi中使用c#上传包含流的MultipartFormDataContent

fkaflof6  于 2023-02-14  发布在  .NET
关注(0)|答案(2)|浏览(424)

下面是一个例子:

  1. using Microsoft.AspNetCore.Mvc;
  2. /// <summary>
  3. /// Eviget controller used for uploading artefacts
  4. /// Either from teamcity or in case of the misc files
  5. /// </summary>
  6. [Route("api/[controller]/[action]")]
  7. [ApiController]
  8. public class UploadDemoController : ControllerBase
  9. {
  10. [HttpPost]
  11. public IActionResult Upload([FromForm] UploadContent input)
  12. {
  13. return Ok("upload ok");
  14. }
  15. }
  16. public class UploadContent
  17. {
  18. public string Id { get; set; }
  19. public string Name { get; set; }
  20. public Stream filecontent { get; set; }
  21. }

以下代码用于上载MultipartFormDataContent

  1. using System.Net.Http.Headers;
  2. HttpClient http = new HttpClient();
  3. MultipartFormDataContent form = new MultipartFormDataContent();
  4. StringContent IdStringContent = new StringContent(Guid.NewGuid().ToString());
  5. form.Add(IdStringContent, "Id");
  6. StringContent NameStringContent = new StringContent($@"foobar");
  7. form.Add(NameStringContent, "Name");
  8. StreamContent TestStream = new StreamContent(GenerateStreamFromString("test content of my stream"));
  9. TestStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "filecontent", FileName = "test.txt" };
  10. TestStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  11. form.Add(TestStream, "filecontent");
  12. //set http heder to multipart/form-data
  13. http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
  14. try
  15. {
  16. System.Console.WriteLine("start");
  17. var response = http.PostAsync("http://localhost:5270/api/UploadDemo/Upload", form).Result;
  18. response.EnsureSuccessStatusCode();
  19. }
  20. catch (System.Exception ex)
  21. {
  22. System.Console.WriteLine(ex.Message);
  23. }

默认情况下,响应为400(错误请求)。
使用下面的控制器选项,请求被发送到rest服务器,这个选项只是说rest服务器应该忽略空值。

  1. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)

流始终为空。(注意:其他值设置正确)

但流实际上是多部分表单数据(fiddler输出)

的一部分
在这种情况下,我需要做什么才能正确Map流?

dhxwm5r4

dhxwm5r41#

请使用IFormFile,而不要使用数据类型Stream
因此,您可以按如下方式访问属性和文件:

  1. var file = input.filecontent // This is the IFormFile file

要将文件持久化/保存到磁盘,可以执行以下操作:

  1. using (var stream = new FileStream(path, FileMode.Create))
  2. {
  3. await file.File.CopyToAsync(stream);
  4. }
wlwcrazw

wlwcrazw2#

这是一个基于ibarcia信息的样本。
我已经创建了两个webapi控制器,允许读取作为MultipartFormDataContent的一部分上传的文件。
第一个方法定义一个属性为[FromForm]的参数,该参数包含IFormFile类型的属性。在第二个实现中,未指定参数,可以通过Request.ReadFormAsync读取文件,然后访问文件

  1. using Microsoft.AspNetCore.Mvc;
  2. /// <summary>
  3. /// Eviget controller used for uploading artefacts
  4. /// Either from teamcity or in case of the misc files
  5. /// </summary>
  6. [Route("api/[controller]/[action]")]
  7. [ApiController]
  8. public class UploadDemoController : ControllerBase
  9. {
  10. [HttpPost]
  11. public async Task<IActionResult> UploadWithoutParameter()
  12. {
  13. IFormCollection formCollection = await this.Request.ReadFormAsync();
  14. //contains id and name
  15. foreach (var form in formCollection)
  16. {
  17. System.Console.WriteLine(form.Key);
  18. System.Console.WriteLine(form.Value);
  19. }
  20. foreach (var file in formCollection.Files)
  21. {
  22. System.Console.WriteLine(file.FileName);
  23. System.Console.WriteLine(file.Length);
  24. }
  25. return Ok("upload ok");
  26. }
  27. [HttpPost]
  28. public async Task<IActionResult> Upload([FromForm] UploadContent input)
  29. {
  30. System.Console.WriteLine(input.Id);
  31. System.Console.WriteLine(input.Name);
  32. using (var stream = new FileStream(@"c:/temp/neutesttext.txt", FileMode.Create))
  33. {
  34. await input.filecontent.CopyToAsync(stream);
  35. }
  36. return Ok("upload ok");
  37. }
  38. public class UploadContent
  39. {
  40. public string Id { get; set; }
  41. public string Name { get; set; }
  42. // public Stream filecontent { get; set; }
  43. public IFormFile filecontent { get; set; }
  44. }
  45. }
展开查看全部

相关问题