简体   繁体   中英

How to upload files in asp.net core web api

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"
}

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");
    }

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 parameter Illustration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM