Asp.Net Core 2.0中的'HttpPostedFileBase'

47

最近我在开发一个使用ReactJS的应用程序,该应用程序调用了一个使用.NET Core 2.0开发的API。

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


可能是MVC 6 HttpPostedFileBase?的重复问题。 - CodeCaster
4个回答

72

在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://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1

IFormFile位于Microsoft.AspNetCore.Http命名空间中。


19

HttpPostedFileBase在ASP.NET Core中不存在。现在应该使用IFormFile。但是,如果您正在使用React之类的客户端框架,那么只有在将请求发送为multipart/form-data时才起作用。如果您要发布JSON,则应将相应于文件属性的JSON成员设置为以Base64字符串编码的文件。在服务器端,然后应绑定到byte[]


11

如果有人通过搜索 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()方法),但我认为这些差异的细节超出了本问题的范围。


7
您还应该能够按以下方式获取文件:
    [HttpPost]
    public ActionResult UploadFiles()
    {
        var files = Request.Form.Files;
        return Ok();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接