Upload file to a folder in ASP.NET Core MVC

Mifdha Milan
2 min readMar 16, 2021

--

The purpose of this article is to show an easy way to use, when needed to upload files in projects. Here I’ll upload the files to a folder and then get the files to anywhere needed from that folder. I’ll be demonstrating the working of this using postman.

1.Create a controller

Here I named the controller as ImageUploadController.cs

Write the following code in the controller to upload the file to a folder in to local storage. I upload the file to a folder named Uploads in desktop, this will create such a folder if it doesn’t exist.

We use IFormFile interface to access individual files uploaded to the application through model binding

get the file path of the required folder to upload as shown below

public class FileUploadAPI{
public IFormFile files { get; set; }
}
[HttpPost]
public async Task<string> Post([FromForm] FileUploadAPI objFile)
{
if (objFile.files.Length > 0)
{
try
{
if (!Directory.Exists(“C:\\Users\\USER\\Desktop\\” + “\\Uploads\\”))
{
Directory.CreateDirectory(“C:\\Users\\USER\\Desktop\\” + “\\Uploads\\”);
}
using (FileStream fileStream = System.IO.File.Create(“C:\\Users\\USER\\Desktop\\” + “\\Uploads\\” + objFile.files.FileName))
{
objFile.files.CopyTo(fileStream);
fileStream.Flush();
var filePath = “C:\\Users\\USER\\Desktop\\Uploads\\” + objFile.files.FileName;
return filePath;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
{
return “Unsuccesssful”;
}
}

2. Run the program, get the URL and check it using postman

from the code file path has been returned. check the Uploads folder to view the .jpg file

3. To get all the files in the Uploads folder,

public class FileModel
{
public string FileName { get; set; }
}
[Route(“getFiles”), HttpGet]
public List<FileModel> Index()
{
string[] filePaths = Directory.GetFiles(Path.Combine(“C:\\Users\\USER\\Desktop\\”, “Uploads/”));
List<FileModel> files = new List<FileModel>();
foreach (string filePath in filePaths)
{
files.Add(new FileModel { FileName = Path.GetFileName(filePath) });
}
return files;
}

I hope this article will be useful for you. Thank you!

--

--

Mifdha Milan
Mifdha Milan

Written by Mifdha Milan

Undergraduate at University of Moratuwa

No responses yet