How to upload and download files on the network server
Many users want to upload some files and download files from the server. Asp.net provides the fileupload control to upload files to the web server. It provides a simple method to upload files to the server. The encoder has not written the entire logic to read and write files to the web server.
Here, I will mention how to use the file upload control to upload files to the server. Add a button to download files from the server. The response object provides the addheader method. You can refer to different types of headers to be passed to the client. Here, you can specify the file name to pass to the client by using the content and attachment configuration attributes. The client Web browser will prompt the user to download the file.
Client Side code: default. aspx
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Table border = "1" cellspacing = "0" cellpadding = "0" id = "TBL">
<Tbody>
<Tr>
<TD>
<Asp: fileupload id = "fileupload1" runat = "server" borderstyle = "solid" forecolor = "black"
Width = "329px" backcolor = "white"/>
</TD>
</Tr>
</Tbody>
</Table>
<Table border = "1" cellspacing = "0" cellpadding = "0" id = "tblbutton">
<Tbody>
<Tr>
<TD>
<Asp: button id = "btnupload" text = "Upload" runat = "server" onclick = "btnupload_click"/>
</TD>
<TD>
<Asp: button id = "btndownload" text = "Download" runat = "server" onclick = "btndownload_click"/>
</TD>
</Tr>
</Tbody>
</Table>
</Div>
</Form>
</Body>
</Html>
Default. aspx. CS
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. IO;
Public partial class _ default: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
}
Protected void btnupload_click (Object sender, eventargs E)
{
String filepath = fileupload1.filename;
String strfilename = "";
If (fileupload1.postedfile! = NULL)
{
Httppostedfile file = fileupload1.postedfile;
// Get the size of the file so you can read the file
Int contentlen = file. contentlength;
If (contentlen> 0)
{
Strfilename = path. getfilename (filepath );
File. saveas (server. mappath (strfilename ));
}
}
}
Protected void btndownload_click (Object sender, eventargs E)
{
String filename = "amazon.txt ";
String filepath = server. mappath (filename );
Response. Clear ();
Response. appendheader ("content-disposition", "attachment; filename =" + filepath );
Response. contenttype = "application/octet-stream ";
Response. writefile (filepath );
Response. Flush ();
Response. End ();
}
}
Hope this will guide you how to upload and download files on the network server.