File or Image Upload is a very common requirement of Web Application and achieving the functionality with the help of REST API is very common practice.
In this article, we will see how we can upload an image into the server folder using ASP.NET Core 3.1 Web API and also how can we download an image or file using Web API.
In the below example I will be demonstrating regarding the image upload or download but the same is applicable for File upload or download.
WebAPI endpoint to upload or download Image into Server Folder
[Route("api/[controller]")][ApiController]public class ImageController : ControllerBase{private readonly IWebHostEnvironment _environment;public ImageController(IWebHostEnvironment environment){_environment = environment;}[HttpPost("UploadFile")]public async Task<string> UploadFile(){try{var file = Request.Form.Files[0];string fName = file.FileName;string path = Path.Combine(_environment.ContentRootPath, "Images", file.FileName);using (var stream = new FileStream(path, FileMode.Create)){await file.CopyToAsync(stream);}return $"{file.FileName} successfully uploaded to the Server";}catch (Exception ex){throw;}}[HttpPost()]public async Task<IActionResult> GetImage(string imageName){Byte[] b;b = await System.IO.File.ReadAllBytesAsync(Path.Combine(_environment.ContentRootPath, "Images", $"{imageName}"));return File(b, "image/jpeg");}}
Let's analyze the above code first the Controller is injected with IWebHostEnvironment which helps us to retrieve the root path of the server.
Both Upload and Download is a POST endpoint and we should have folder named Images at the root of the application folder.
In the Upload endpoint, we are returning a string indicating a success message of the File uploaded, and in the download endpoint, we are returning a File Result.
In order to test the above endpoint, we will be using Postman software which is very widely used to test the REST API endpoint.
Image Upload Endpoint
URL: http://localhost:5000/api/image/uploadfile
Type: POST
Body: Image file
Below is the Postman screenshot
Please make sure you select File from the key dropdown.
We will get 200 OK responses once the image is uploaded successfully into the Image folder on the server
Image Download Endpoint
URL: http://localhost:5000/api/image?imageName=codetosolutions.jpg
Type: POST
Body: null
Please note we are providing the name of the image using query string in the endpoint address.
As we can see in the above screenshot we are able to download the image successfully in the postman.
Hope you have understood to implement image upload and download in .Net Core Web API.
Share This Post
Support Me