I am following a tutorial to download file from server. But having some trouble. I must be doing some silly mistake..!!
This is the link that I am following: http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx
The requirement is; User will click on a link, the site will take them to a details page. On that details page, there will be a download link. When user will click on that download link, the file will be downloaded.
The problem is, when I click the download link, it does not download the original file. Rather it downloads a HTML file. If I click the HTML file, it shows garbage.
This is my code:
Action:
public ActionResult Download(string path,string name)
{
return new DownloadResult { VirtualPath = path, FileDownloadName = name };
}
The DownloadResult class
public class DownloadResult : ActionResult
{
public DownloadResult()
{
}
public DownloadResult(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath
{
get;
set;
}
public string FileDownloadName
{
get;
set;
}
public override void ExecuteResult(ControllerContext context)
{
if (!String.IsNullOrEmpty(FileDownloadName))
{
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + this.FileDownloadName);
}
string filePath = this.VirtualPath; //context.HttpContext.Server.MapPath(this.VirtualPath);
context.HttpContext.Response.TransmitFile(filePath);
}
}
The only difference from the tutorial and my code is I am using the actual server path.
Any idea??
If you need to send a file to the client and you know the path, use the FilePathResult:
public ActionResult Download(string path, string name)
{
return new FilePathResult(path, contentType) {
FileDownloadName = name
}
}
Note that you need to know the content type. If you really don't know, you can use application/octet-stream which makes the browser treat it as a binary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With