How to download file from Server using ASP.NET and C#
Here i am providing the reference code to download file from our web application.......What is Binary reader
Binary reader reads data in primitive manner in binary format with encoding, convert whole file in binary format.
What is Response Object
This object gets the current HTTP response for current web request.
Following are some different methods that we can use for download file from server.
What is Server.MapPath
The File paths on local development machine are not the same as they are on your server, and from client machine you can not get the physical file path of exist on server.
for that we have to use Server.MapPath(//fileName); MapPath returns physical paths and file location.
e.g.
string a = HttpContext.Current.Server.MapPath("~/App_Data/Example.xml");
output is physical path
D:\website\App_Data_Example.xml
Code view
here is code to download file from server (you should have a file exist on server)
string path = Server.MapPath("1.pdf"); //get physical file path from server
string name = Path.GetFileName(path); //get file name
string ext = Path.GetExtension(path); //get file extension
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".GIF":
type = "image/GIF";
break;
case ".pdf":
type = "Application/pdf";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
Default:
type="";
break;
}
}
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
if (type != "")
Response.ContentType = type;
Response.WriteFile(path);
Response.End(); //give POP to user for file downlaod
here is output of above code
using above code you will get a POP up to save the file. Here we get content type of file and then append header to response object.
If you want to use the above code to support other file types, you must change the value in the ContentType string so that it points the appropriate file format.
The syntax of this string is usually formatted as "type/subtype,"
where "type" is the general content category and "subtype" is the specific content type.
For a full list of supported content types, refer to your Web browser documentation or the current HTTP specification
Compatibility
This code is compatible to Internet Explorer, Firefox, Opera, Chrome.
Comments
Post a Comment