Download file in asp.net
בתפוז נשאלה שאלה:
מה הקוד שצריך לכתוב כדי להוריד קובץ בעזרת לינק פשוט ?
אני נתקל הרבה פעמים בשאלה הזאת - ולכן אני כותב כאן את דוגמת הקוד.
צריך לייצר handler ולכתוב ב - ProcessRequest את הקוד הבא:
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["filename"];
FileInfo fi = new FileInfo(fileName);
context.Response.ContentType = "application/x-rar-compressed";
context.Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename=download{0}", fi.Name));
context.Response.WriteFile(fileName);
context.Response.End();
}
כמובן שה - ContentType צריך להיות לפי סוג הקובץ (אפשר לבדוק בעזרת המאפיין Extension של FileInfo.
קוד ה - html
<a href="MyHandler.ashx?filename=C:\MyFile.rar">Download</a>