dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.62k stars 25.31k forks source link

Need separate File Uploads topic for Core WebAPI2.1 #8742

Closed zhenweied09 closed 6 years ago

zhenweied09 commented 6 years ago

[As a beginner of Core2.1 WebAPI, I want to know how to download/ upload multiple images.

Unfortunately I can not find out the desired topic related in either the WebAPI section or any other sections, except the “File Uploads” in MVC.

The recommended approach for multiple files Uploads is using IEnumerable or List is not working in Core WebAPI 2.1 somehow instead of keeping responding 400 errors.

After days of investigation on the API reference document I solved the problem by using IFormFileCollection instead.

So there should be a separate topic of. File Uploads in the WebAPI sections instead of just in MVC, or some more explanation of the difference between IEnumerable or IFormFileCollection. ]


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

zhenweied09 commented 6 years ago
   [HttpPost("Photos")]
    public async Task<IActionResult> UploadPhotosAsync(List<IFormFile> files)
    {
        long size = files.Sum(f => f.Length);
        var fileFolder = Path.Combine(_env.WebRootPath, "Photos");

        if (!Directory.Exists(fileFolder))
              Directory.CreateDirectory(fileFolder);

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss")+
                               Path.GetExtension(file.FileName);
                var filePath = Path.Combine(fileFolder, fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }
        return Ok(new { count = files.Count, size});
    }
}

Error:

Microsoft.AspNetCore.MVC.Infrastructure.ObjectResultExecutor[1] Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.SerializableError'.

guardrex commented 6 years ago

Hello @zhenweied09 ... Thanks for commenting. There's an open issue to address the file uploads topic at: #5331. Let's leave this open, and I'll add it to the list there. I don't think the subject of Web API would call for a separate topic, but the doc author can make that determination when it comes time to work that issue.

In the meantime tho, open your question on a support forum, such as Stack Overflow. There are only a handful of doc authors here. You'll get great visibility and probably a much faster answer/assistance there.

Rick-Anderson commented 6 years ago

For file uploads, you'd normally want an UI - so Web API wouldn't be the right place. Closing issue.