TechieClues TechieClues
Updated date Feb 03, 2024
ASP.NET Core MVC provides an easy way to upload and download files using inbuilt .Net core classes and methods. The sample program gives you an overall idea about the file upload and download functionality in ASP.NET MVC.

Download File(s):

FileUploadDownload.rar

In this article, we will see how to upload and download files using the ASP.NET Core MVC application. The below example explains the file upload and download functionality.

Step 1:

Create a new project using the ASP.NET Core Web application template and select the model view controller option as shown below,

Step 2:

Modify the Index.cshtml file and add the below code to include the file upload control and buttons.

<!-- In order to post files to the server we should use form with post method, also need to add multipart/form-data encoding.
	 Otherwise the files will not be sent to the server. -->
<form method="post" enctype="multipart/form-data">
	<input type="file" name="files" multiple />
	<button type="submit">Upload</button>
</form>

<!-- To show the success message to the user  -->
@if (ViewBag.Message != null)
{
	<div class="alert alert-success" style="margin-top:50px">
		@ViewBag.Message
	</div>
}

In order to post the files to the server, we should use form with post method, also need to add multipart/form-data encoding, otherwise the files will not be sent to the server.

We have also added <div> to show the success message to the user for their reference.

Step 3:

To display uploaded files or existing file list on the screen, add the below code in Index.cshtml file,

<p style="margin-top: 50px">List of Files</p>
<!-- Get all the files from the server -->
<ul>
	@foreach (var item in Model.Files)
	{
		<li>
			<a asp-action="Download"
			   asp-route-filename="@item.Name">
				@item.Name
			</a>
		</li>
	}
</ul>

Step 4: 

Add a HomeController.cs and action method to upload the files to the server.

[HttpPost]
public IActionResult Index(IFormFile[] files)
{
	// Iterate each files
	foreach (var file in files)
	{
		// Get the file name from the browser
		var fileName = System.IO.Path.GetFileName(file.FileName);

		// Get file path to be uploaded
		var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);

		// Check If file with same name exists and delete it
		if (System.IO.File.Exists(filePath))
		{
			System.IO.File.Delete(filePath);
		}

		// Create a new local file and copy contents of uploaded file
		using (var localFile = System.IO.File.OpenWrite(filePath))
		using (var uploadedFile = file.OpenReadStream())
		{
			uploadedFile.CopyTo(localFile);
		}
	}
	ViewBag.Message = "Files are successfully uploaded";

	// Get files from the server
	var model = new FilesViewModel();
	foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
	{
		model.Files.Add(
			new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
	}
	return View(model);
}

ASP.NET Core provides IFormFile interface to upload one or multiple files. As discussed in Step 2, the HTML form must have the encoding type set to multipart/form-data and an input element with the attribute set to multiple for multiple file uploading.

If you want to upload a single file then set the input element with file attribute.

<form method="post" enctype="multipart/form-data">
	 <input type="file" name="file" /> 
	<button type="submit">Upload</button>
</form>

Step 5:

In order to download files from the server, add the below code to the controller.

// Download file from the server
public async Task<IActionResult> Download(string filename)
{
	if (filename == null)
		return Content("filename is not availble");

	var path = Path.Combine(Directory.GetCurrentDirectory(), "upload", filename);

	var memory = new MemoryStream();
	using (var stream = new FileStream(path, FileMode.Open))
	{
		await stream.CopyToAsync(memory);
	}
	memory.Position = 0;
	return File(memory, GetContentType(path), Path.GetFileName(path));
}

// Get content type
private string GetContentType(string path)
{
	var types = GetMimeTypes();
	var ext = Path.GetExtension(path).ToLowerInvariant();
	return types[ext];
}

// Get mime types
private Dictionary<string, string> GetMimeTypes()
{
	return new Dictionary<string, string>
	{
		{".txt", "text/plain"},
		{".pdf", "application/pdf"},
		{".doc", "application/vnd.ms-word"},
		{".docx", "application/vnd.ms-word"},
		{".xls", "application/vnd.ms-excel"},
		{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
		{".png", "image/png"},
		{".jpg", "image/jpeg"},
		{".jpeg", "image/jpeg"},
		{".gif", "image/gif"},
		{".csv", "text/csv"}
	};
}

Also, add the below code inside the Index action method to get the files from the server on load of the page.

public IActionResult Index()
{
	// Get files from the server
	var model = new FilesViewModel();
	foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
	{
		model.Files.Add(
			new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
	}
	return View(model);
}

Output:

To Upload a single file use file upload control, select a file, and click the upload button :

The file is uploaded successfully and listed on the screen.


To Upload multiple files use file upload control, select files click the upload button.

The files have been successfully uploaded and listed below on the screen. If you want to download the file then click the file hyperlink which you want to download.


 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!