How to upload files in asp.net core web api

2020-03-26 08:31发布

问题:

I am trying to implement a file upload in Asp.net Core. See my endpoit below:

    [HttpPost("upload")]
    [AllowAnonymous]
    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);
                }
            }
        }


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

When I test it using Postman I get the following result even if I select any file:

{
   "count": 0,
   "size": 0,
   "filePath": "/var/folders/24/rmgj9ypj37709tnhxr2hgtfr0000gn/T/tmpX0SwbF.tmp"
}

回答1:

This should guide you in the right direction. The method is receiving a jQuery post object.

    [HttpPost]
    public async Task<IActionResult> ReadFileHeaders(IFormFile file)
    {
        if (file != null)
        {
            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);
                // Now the file is loaded into the stream variable
            }
        }

        return BadRequest("File required");
    }


回答2:

There is no problem on the code. But when using postman(or similar) you will need to have the same name("files" on your case) on the parameterIllustration