【问题标题】:'HttpPostedFileBase' in Asp.Net Core 2.0Asp.Net Core 2.0 中的“HttpPostedFileBase”
【发布时间】:2018-06-25 10:22:12
【问题描述】:

我最近正在开发一个调用 API(使用 .NET Core 2.0 开发)的 ReactJS 应用程序。

我的问题是如何在 .NET Core 2.0 API 中使用 HttpPostedFileBase 以获取文件内容并将其保存在数据库中。

【问题讨论】:

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0


【解决方案1】:

在 ASP.NET Core 2.0 中没有HttpPostedFileBase,但可以使用IFormFile

[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
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

更多:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1

IFormFile 位于以下命名空间Microsoft.AspNetCore.Http

【讨论】:

    【解决方案2】:

    HttpPostedFileBase 在 ASP.NET Core 中不存在。您现在应该改用IFormFile。但是,这仅在您以multipart/form-data 发送请求时才有效,如果您正在使用像 React 这样的客户端框架,您可能不会这样做。如果您发布 JSON,您应该设置与您的文件属性对应的 JSON 成员,并将文件编码为 Base64 字符串。服务器端,你应该绑定到byte[]

    【讨论】:

      【解决方案3】:

      你也应该能够得到这样的文件:

          [HttpPost]
          public ActionResult UploadFiles()
          {
              var files = Request.Form.Files;
              return Ok();
          }
      

      【讨论】:

        【解决方案4】:

        如果有人通过搜索 HttpPostedFileBase 找到了这个,那可能是你熟悉编写类似这样的 ASP.NET 控制器方法:

        public async Task<IActionResult> DoThing(MyViewModel model, HttpPostedFileBase fileOne, HttpPostedFileBase fileTwo)
        {
           //process files here
        }
        

        如果你想在 ASP.NET Core 中写一个等价的,那么你可以这样写:

        public async Task<IActionResult> DoThing(MyViewModel model, IFormFile fileOne, IFormFile fileTwo)
        {
           //process files here
        }
        

        即方法签名所需的唯一更改是将HttpPostedFileBase 替换为IFormFile。然后,您将需要修改您的方法以使用新的参数类型(例如,HttpPostedFileBase 具有 InputStream 属性,而 IFormFile 具有 OpenReadStream() 方法)但我认为这些差异的细节超出了范围这个问题。

        【讨论】:

          猜你喜欢
          • 2020-07-25
          • 2018-06-20
          • 2018-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-17
          相关资源
          最近更新 更多