How to Upload files in ASP.NET Core Web API using C#
By FoxLearn 9/4/2024 8:54:30 AM 7.95K
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
You need a controller that will handle the file upload. Let's create a FileController
In the Controllers
folder, create a new file named FileController.cs
.
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, Implement the file upload logic in the controller. 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.
You can test your file upload endpoint using tools like Postman.
Using Postman:
- Set the method to
POST
. - Enter the URL to your API endpoint (e.g.,
https://localhost:[port]/api/file/upload
). - Select
Body
and thenform-data
. - Add a key named
file
, set the type toFile
, and choose a file to upload. - Send the request and check the response.