asp.net core 中使用表单数据上传文件

Ary*_*yan 5 javascript angularjs asp.net-core

我正在尝试将带有表单数据的文件从 Angular 1.5x 上传到 .net core Web api 控制器。我的控制器看起来像这样

    [HttpPost]public async Task<ObjectResult> Create(TutorModel model) 
    {
    }
Run Code Online (Sandbox Code Playgroud)

我的发帖方法是

    [HttpPost]public async Task<ObjectResult> Create(TutorModel model) 
    {
    }
Run Code Online (Sandbox Code Playgroud)

现在,当它发布到控制器时,模型不包含属性值。如果我观看 Request.Form.Files,我会在控制器中获得上传的文件。将模型发送到上述方法的最佳方法是什么?有什么指针吗?谢谢

Ahm*_*mar 3

Asp.net core 文档简要介绍了这个主题。

你的控制器动作会是这样的。

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
   long size = files.Sum(f => f.Length);

   // full path to file in temp location
   var filePath = Path.GetTempFileName();

   foreach (var formFile in files)
   {
      if (formFile.Length > 0)
      {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
            await formFile.CopyToAsync(stream);
         }
      }
    }

     // process uploaded files

    return Ok(new { count = files.Count, size, filePath});
}
Run Code Online (Sandbox Code Playgroud)

其中 IFormFile 具有这些属性

   public interface IFormFile
   {
     string ContentType { get; }
     string ContentDisposition { get; }
     IHeaderDictionary Headers { get; }
     long Length { get; }
     string Name { get; }
     string FileName { get; }
     Stream OpenReadStream();
     void CopyTo(Stream target);
     Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
   }
Run Code Online (Sandbox Code Playgroud)

注意:在关系数据库中存储二进制数据时要小心,因为它会对性能产生不利影响。

在这里阅读详细文章 文件上传