In this article i will show you how you can download the uploaded file in wwwroot folder in your asp.net core 6 / mvc application.
In my previous article i have shown you how you can upload file in asp.net core 6 using c# and other article like upload file and rename it before uploading in wwwroot folder in asp.net core .
Other related are as follows: Asp.Net Core 6 : Rename / Change File or Image Name and Upload in wwwroot Using C#.Net, ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery, Asp.Net Core 6 : Upload File in User Created Folder (Folder Outside wwwroot) Using C#, File Upload in wwwroot Folder Using Input File Control(HTML) in Asp.Net Core 6/MVC Using C#
Now for this article we will create a new asp.net core application and in wwwroot folder we will add a static file in it. This file we will download on button click on our asp.net core application.
Now on controller end we will create a httpget method.
[HttpGet] public IActionResult Index() {
return View(); } |
After this we will create a view and and add link or button control. On click on this control we will download the file.
@{
ViewData["Title"] = "Page"; } <div class="text-center"> <h1>Click Link to download file</h1><br /><br /> <a href="/Home/Index/" title="Download file"><b>DOWNLOAD</b></a> </div> |
After this we will write code to download the file. For this we will create a HttpPost method in controller.
public IActionResult DownloadFile() { var memory = DownloadSinghFile("TextFile.txt", "wwwwroot"); return File(memory.ToArray(), "text/plain", "TextFile.txt"); } private MemoryStream DownloadSinghFile(string filename, string uploadPath) { var path = Path.Combine(Directory.GetCurrentDirectory(),
uploadPath, filename); var memory = new
MemoryStream(); if (System.IO.File.Exists(path)) { var net = new System.Net.WebClient(); var data = net.DownloadData(path); var content = new System.IO.MemoryStream(data); memory = content; } memory.Position = 0; return memory; } |
In above code i have passed the file detail and return type of the function is MonoryStream. After that i have user File return type to convert the memorystream in file. In this file return type you must pass the type and file name. Here is the list of file type which you can refer.
{".txt", "text/plain"}, {".pdf", "application/pdf"}, {".doc", "application/vnd.ms-word"}, {".docx", "application/vnd.ms-word"}, {".xls", "application/vnd.ms-excel"}, {".xlsx", "application/vnd.ms-excel"}, {".png", "image/png"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".gif", "image/gif"}, {".csv", "text/csv"}, {".zip", "application/zip"} |
Now we have done run the code to check the output.
Now click on download link to download the file.
Download
0 comments:
Please let me know your view