Created
August 23, 2015 06:32
-
-
Save shuvoranger/8215c5af4f55eb1d6eed to your computer and use it in GitHub Desktop.
Download File from Specific Location in Asp.net MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<ActionResult> GeneratePayment() | |
{ | |
string fileName = "Book.pdf"; | |
try | |
{ | |
if (!string.IsNullOrEmpty(fileName)) | |
{ | |
Response.ContentType = "Application/pdf"; | |
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); | |
Response.TransmitFile(Server.MapPath("~/Files/" + fileName)); | |
Response.End(); | |
ViewBag.Success = "Downloaded Successfully"; | |
ViewBag.ReturnUrl = Url.Action("GeneratePayment", "ControllerName"); | |
} | |
else | |
{ | |
ViewBag.Success = "Sorry! No File available."; | |
ViewBag.ReturnUrl = Url.Action("GeneratePayment", "ControllerName"); | |
} | |
} | |
catch | |
{ | |
} | |
return View("Message"); | |
} | |
//Get The Things More Dynamic when You Don't Know The ContentType of The File. | |
public async Task<ActionResult> GeneratePayment() | |
{ | |
string fileName = "Book.pdf"; | |
string fileExtension = ".pdf"; | |
try | |
{ | |
if (!string.IsNullOrEmpty(fileName)) | |
{ | |
Response.ContentType = GetContentType(fileExtension); | |
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); | |
Response.TransmitFile(Server.MapPath("~/Files/" + fileName)); | |
Response.End(); | |
ViewBag.Success = "Downloaded Successfully"; | |
ViewBag.ReturnUrl = Url.Action("GeneratePayment", "ControllerName"); | |
} | |
else | |
{ | |
ViewBag.Success = "Sorry! No File available."; | |
ViewBag.ReturnUrl = Url.Action("GeneratePayment", "ControllerName"); | |
} | |
} | |
catch | |
{ | |
} | |
return View("Message"); | |
} | |
private string GetContentType(string fileExtension) | |
{ | |
if (string.IsNullOrEmpty(fileExtension)) | |
return string.Empty; | |
string contentType = string.Empty; | |
switch (fileExtension) | |
{ | |
case ".htm": | |
case ".html": | |
contentType = "text/HTML"; | |
break; | |
case ".txt": | |
contentType = "text/plain"; | |
break; | |
case ".doc": | |
case ".rtf": | |
case ".docx": | |
contentType = "Application/msword"; | |
break; | |
case ".xls": | |
case ".xlsx": | |
contentType = "Application/x-msexcel"; | |
break; | |
case ".jpg": | |
case ".jpeg": | |
contentType = "image/jpeg"; | |
break; | |
case ".gif": | |
contentType = "image/GIF"; | |
break; | |
case ".pdf": | |
contentType = "application/pdf"; | |
break; | |
} | |
return contentType; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment