ASP. NET implements file upload and download, and asp.net implements File Upload
Recently, a university website involves the need to upload and download files (the specific requirement is: the notification published by the website should be added to each notification in the background, to display and download attachments on the front-end, I have only learned about the upload theory. Here I will explore the introduction and share with you the results.
Note: In this example, a simple three-tier structure is used to transmit values between layers using entities. In addition, this method not only succeeds during local testing, but also can be deployed on the server for remote file upload and download.
A database table is created to store the attachment information:
Field |
Description |
Region ID |
Attachment ID |
CommonName |
Attachment name |
Administrative address |
Storage attachment address |
NoticeID |
ID of the notification to which the attachment belongs |
ASP. NET implements File Upload
Front end
The interface is very simple, just put a file type <input> and a button, and add a click event (btnUpLoad_Click) for this button, such:
Code:
<Input id = "UpLoad" type = "file" runat = "server"/> <asp: button runat = "server" Text = "Upload" ID = "btnUpLoad" OnClick = "btnUpLoad_Click"/>
Background
Then, write the code in the upload button in the background and click the event UpLoad_Click. Let's take a general idea:
1. Obtain the physical path of the file to be uploaded on the local machine based on the <input> Control of the file type;
2. Use the string truncation method in this physical path to obtain the file name (the path obtained in the first step is the absolute path of the local machine, which is invalid on the server, so here we only need to get the file name );
3. Use the SaveAs () method of the <input> Control attribute PostedFile of the file type to store the corresponding file in the specified folder on the server.
Core code:
Protected void btnUpLoad_Click (object sender, EventArgs e) {// retrieve the local path of the selected file string fullFileName = this. upLoad. postedFile. fileName; // extract the file name string fileName = fullFileName from the path. substring (fullFileName. lastIndexOf ("\") + 1); // specifies the format of the uploaded file. string type = fullFileName. substring (fullFileName. lastIndexOf (". ") + 1 ); if (type = "doc" | type = "docx" | type = "xls" | type = "xlsx" | type = "ppt" | type = "Pptx" | type = "pdf" | type = "jpg" | type = "bmp" | type = "gif" | type = "png" | type = "txt" | type = "zip" | type = "rar ") {// save the file in the files folder under the root directory of the Server string saveFileName = Server. mapPath ("/files") + "\" + fileName; UpLoad. postedFile. saveAs (saveFileName); Page. clientScript. registerStartupScript (Page. getType (), "message", "<script language = 'javascript 'defer> alert ('file uploaded successfully! '); </Script> "); // The directory that stores the attachment of the corresponding notification to the database, BLL. news. insertAnnexBLL insertAnnex = new BLL. news. insertAnnexBLL (); entity annex = new entity (); // create the annex object of the attachment. attachment name = fileName; // The Name Of The attachment annex. stored content = saveFileName; // The storage path of the attachment annex. noticeId = noticeId; // the "Notification" ID of the attachment is known here. insertAnnex (annex); // stores entities in the database (in fact, it refers to the process of inserting these attributes of entities into the database. The specific BLL layer and DAL Layer Code will not be mentioned here )} else {Page. clientScript. registerStartupScript (Page. getType (), "message", "<script language = 'javascript 'defer> alert ('select the correct format'); </script> ");}}
Download files using ASP. NET
The preceding operations can be used to store controls into the database. The following figure shows how to store the controls in the database:
These controls are displayed on the page as follows:
Click the attachment and the browser prompts you to download it:
Front-end:
As required, each notification can contain several attachments, and the front-end uses the repeter control to display multiple attachments:
Code:
<Asp: Repeater ID = "rptAnnex" runat = "server"> <ItemTemplate> <% -- add sequence number for repeter -- %> attachment: <% # Container. itemIndex + 1%> <asp: LinkButton ID = "lbtnDownLoad" runat = "server" OnCommand = "lbtnDownLoad_Command" CommandArgument = "<% # (Model. entity) Container. dataItem ). response content %> "> <% # (Model. entity) Container. dataItem ). customization name %> </asp: LinkButton> <br/> </ItemTemplate> </asp: Repeater>
Background
ASP. NET can be downloaded in multiple ways (for more information, see ASP. NET File Download methods), here uses the stream download method (refer to the article "Asp.net download instance"):
Using System. IO; protected void lbtnDownLoad_Command (object sender, CommandEventArgs e) {// define the file name string fileName = ""; // obtain the address of the file on the server string url = e. commandArgument. toString (); // determines whether the transfer address is empty. if (url = "") {// The system prompts "this file is not available for download" Page. clientScript. registerStartupScript (Page. getType (), "message", "<script defer> alert ('the file is not available for download now! '); </Script> "); return;} // determines whether the obtained url is an address, not a file name if (url. indexOf ("\")>-1) {// get the fileName = url. substring (url. lastIndexOf ("\") + 1);} When else {// url is the file name, get the file name fileName = url ;} // download the file FileStream fileStream = new FileStream (@ url, FileMode. open); byte [] bytes = new byte [(int) fileStream. length]; fileStream. read (bytes, 0, bytes. length); fileStream. close (); Response. contentType = "application/octet-stream"; // notify the browser to download Response. addHeader ("Content-Disposition", "attachment; filename =" + fileName); Response. binaryWrite (bytes); Response. flush (); Response. end ();}
This is all done. Please share a better method!
To learn how aspnet can upload and download files, it is best to provide detailed source code.
Upload: HttpPostedFile postFile = Upload. PostedFile; postFile. SaveAs (MapPath ("path "));
Download:
Public static void DownLoadFile (string path)
{
Path = HttpContext. Current. Server. MapPath (path );
System. IO. FileInfo file = new System. IO. FileInfo (path );
HttpContext. Current. Response. Clear ();
HttpContext. Current. Response. AddHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. UrlEncode (file. Name ));
HttpContext. Current. Response. AddHeader ("Content-Length", file. Length. ToString ());
HttpContext. Current. Response. ContentType = "application/octet-stream ";
HttpContext. Current. Response. WriteFile (file. FullName );
HttpContext. Current. Response. End ();
}
How does aspnet download uploaded files?
FileInfo info = new FileInfo (filePath );
Long fileSize = info. Length;
Response. Clear ();
Response. ContentType = "application/octet-stream ";
Response. AddHeader ("Content-Disposition", "attachement; filename =" + fileName );
// Specify the file size
Response. AddHeader ("Content-Length", fileSize. ToString ());
Response. WriteFile (filePath, 0, fileSize );
Response. Flush ();
Response. Close ();
Filepath is the file path you just uploaded. fileName is the file name.