ASP. NET implements file upload and download
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 typeAnd a button, and add a click event (btnUpLoad_Click) for this button, such:
Code:
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. According to the file typeControl to obtain the physical path of the file to be uploaded on the local machine;
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 file typeThe SaveAs () method of the control property PostedFile stores the corresponding files 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 | typ E = 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>); // directory of the attachment that stores 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:
<% -- Add sequence number for repeter -- %> attachment: <% # Container. ItemIndex + 1% >><%# (Model. entity) Container. DataItem). Container name %>
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 ('this 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 file name fileName = url. substring (url. lastIndexOf (\) + 1);} When else {// url is a 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 ();}