3

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
  • Provide more information, like how is the request you are sending expected, which mime type you used etc. Commented Jul 16, 2017 at 20:09

2 Answers 2

2

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");
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.