ASP.NET Core: How to Upload files in ASP.NET Core Web API using C#
By FoxLearn 11/10/2019 4:02:35 AM 7.65K
To create a Web API upload file in ASP.NET Core. First, You need to know how to create an ASP.NET Core project in Visual Studio. You can view this post: Getting Started with ASP.NET Core 3.0
After finishing creating an ASP.NET Core project, you can create a Web API by right-clicking on Controller folder, then select Add => Controller...
Select API Controller - Empty => Add
Enter your controller name, then click Add button.
[Route("api/[controller]/[action]")] [ApiController]
Modifying your Web API Route as shown above. If you want to call your web api you should enter https://localhost:port/api/file/upload in the web browser.
Next, You need to declare a _webHostEnvirnoment variable that allows you to get the root path, then assign the variable to it in the constructor of your controller.
private readonly IWebHostEnvironment _webHostEnvironment; public FileController(IWebHostEnvironment webHostEnvironment) { this._webHostEnvironment = webHostEnvironment; }
Finally, Create an upload method allows you to upload a file to web server via web api controller.
[HttpPost] public async Task<IActionResult> Upload([FromForm]IFormFile file) { var path = $"{this._webHostEnvironment.WebRootPath}\\files"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); FileInfo fileInfo = new FileInfo(file.FileName); var fullPath = Path.Combine(path, fileInfo.Name); if (!System.IO.File.Exists(fullPath)) { using (FileStream fileStream = new FileStream(fullPath, FileMode.Create)) { await file.CopyToAsync(fileStream); } return new JsonResult(new { FileName = fileInfo.Name }); } return BadRequest(); }
You can modify the file name to ensure it does not dublicate file name on the web server. Finally, You need to return the file name or anything else when uploading the file successfully.
- Windows Forms: How to Upload a file to Web API in C#
- How to Call and Consume Web API in Winform using C#
- How to implement simple Memory Cache for Web API
- How to use Web API JWT Token
- How to fix 'The underlying connection was closed: An unexpected error occurred on a send'
- Windows Forms: Consume Web API In Winform For File Handling in C#