'HttpPostedFileBase' in Asp.Net Core 2.0

2020-07-02 09:01发布

I'm recently working on a ReactJS app that's calling an API (developed with .NET Core 2.0).

My question is how to use HttpPostedFileBase in an .NET Core 2.0 API in order to get file content and save it in database.

4条回答
神经病院院长
2楼-- · 2020-07-02 09:30

You don't have HttpPostedFileBase in ASP.NET Core 2.0, but you can use 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});
}

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

IFormFile is in the following namespace Microsoft.AspNetCore.Http.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-02 09:39

You should also be able to get the files like this :

    [HttpPost]
    public ActionResult UploadFiles()
    {
        var files = Request.Form.Files;
        return Ok();
    }
查看更多
够拽才男人
4楼-- · 2020-07-02 09:51

HttpPostedFileBase doesn't exist in ASP.NET Core. You should use IFormFile now, instead. However, that only works when you send the request as multipart/form-data, which you're likely not doing if you're working with a client-side framework like React. If you're posting JSON, you should set the JSON member that corresponds with your file property with the file encoded as a Base64 string. Server-side, you should then bind to byte[].

查看更多
forever°为你锁心
5楼-- · 2020-07-02 09:53

If anyone finds this by searching for HttpPostedFileBase it's possibly you're familiar with writing ASP.NET controller methods something like this:

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

If you're wanting to write an equivalent in ASP.NET Core then you can write it like this:

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

i.e. the only change needed to the method signature is replacing HttpPostedFileBase with IFormFile. You will then need to modify your method to work with the new parameter type (e.g. HttpPostedFileBase has an InputStream property, whereas IFormFile has a OpenReadStream() method) but I think the details of those differences are beyond the scope of this question.

查看更多
登录 后发表回答