cool hit counter ASP. NET implementation of file upload and download_Intefrankly

ASP. NET implementation of file upload and download


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/40785429

Recently made a college website involves the need to upload and download files (specific requirements: the site announced the notice, in the background to be able to add attachments to each notice, in the foreground to be able to display and download attachments), before just learning about the upload of theoretical knowledge, here practice a little under, and share the results with you.

beforehand instructions: This example uses a simple three-tier structure, Layer to layer is using entities to pass values。 And not only does this method work when tested locally, and can be deployed on servers, for off-site upload and downloading documents。

A special database table was made to store information about the annexes.

(numeric, data) field

instructions

AnnexID

Annex ID

AnnexName

Name of annex

AnnexAddress

Address for storing attachments

NoticeID

annex affiliated“ notices” ofID

ASP.NET realize upload documents

front end

The interface is very simple, Just put one in.file type<input> and a button, furthermore because of This button adds a click event(btnUpLoad_Click), as shown below:

Code.

    <input id="UpLoad" type="file" runat="server" />
    <asp:Button runat="server" Text=" upload" ID="btnUpLoad" OnClick="btnUpLoad_Click" />

back office

Then there's the code in the backend that writes the upload button click event UpLoad_Click, starting with the general idea that

1、 depending onfile type<input> The control gets the information that will be upload Physical path of the file on the local machine;

2. obtain the filename in this physical path by intercepting the string (the path obtained in the first step is an absolute path on the local machine, which is not valid on the server, so here we only need to obtain the filename).

3、 take advantage offile type<input> Control PropertiesPostedFile ofSaveAs() method to store the corresponding files to the specified folder in 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;
             // Truncate the filename from the path
            string fileName = fullFileName.Substring(fullFileName.LastIndexOf("\") + 1);
             // Limit 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 files in the files folder in the root directory in 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 for storing attachments to the corresponding notifications in the database
                BLL.news.InsertAnnexBLL insertAnnex = new BLL.news.InsertAnnexBLL();
                 AnnexEntity annex=new AnnexEntity();      // Create the attached entity
                 annex. AnnexName=fileName;                //Name of attachment
                 annex. AnnexContent=saveFileName;         // Storage path for attachments
                 annex. NoticeId = noticeId;               // The ID of the "notification" to which the attachment belongs is known here
                 insertAnnex.InsertAnnex(annex);          // deposit the entity into the database (actually it is the process of inserting these attributes of the entity into the database, the code of the specific BLL and DAL layers will not be described here)
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert(' Please select the correct format');</script>");
            }
        }

ASP. NET implementation to download files

The above operation has made it possible to store one attachment in the database, and a screenshot of the storage in the database gives you.

The following is going to display these attachments on the page, and the page will be displayed as follows.

clicking annex, Browser prompts to download:

front of the house

In terms of demand, Each published notice can contain several annex, the whole of front of the house used uprepeter control to display multiple annex:

Code.

    <asp:Repeater ID="rptAnnex" runat="server">
         <ItemTemplate>
             <%-- because ofrepeter Add serial number--%>
              annex:<%#Container.ItemIndex + 1 %>       
             <asp:LinkButton ID="lbtnDownLoad" runat="server" OnCommand="lbtnDownLoad_Command" CommandArgument="<%#((Model.AnnexEntity)Container.DataItem).AnnexContent %>"><%#((Model.AnnexEntity)Container.DataItem).AnnexName %></asp:LinkButton>
             <br />
         </ItemTemplate>
     </asp:Repeater>

back office

ASP. NET can download files in a variety of ways (for details, see ASP. NET Several Ways to Download Files ), a streaming download is used here (refer to the article Asp.net Download Examples):

 using System.IO;
    protected void lbtnDownLoad_Command(object sender, CommandEventArgs e)
        {
             // Define the file name  
            string fileName = "";
             // Get the address of the file on the server  
            string url = e.CommandArgument.ToString();

            //  Determine if the transmission address because of vacant  
            if (url == "")
            {
                 // Prompt "This file is not available for download"  
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script defer>alert(' This document is not available for download at this time!');</script>");
                return;
            }
            //  Determine if the acquired because of address, Instead of the file name  
            if (url.IndexOf("\") > -1)
            {
                 // Get the file name  
                fileName = url.Substring(url.LastIndexOf("\") + 1);
            }
            else
            {
                // url because of When the file name, Get the file name directly  
                fileName = url;
            }
             // Downloading files as a character stream  
            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";

             // Notification of browser downloads 
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();     
        }

control upload Size of the file

The first two steps basically already enable the file upload and download, In addition to these, Control is also needed upload Size of the file, By default upload File Size Limit because of4M, Here it is possible to set up a configuration file in theweb.config Modification in, (located) athttpRuntime The following attributes can be added to the node:

<configuration>
  <system.web>  
    <httpRuntime executionTimeout="300" maxRequestLength="51200" useFullyQualifiedRedirectUrl="false" />
  </system.web>
</configuration>

The value of the executionTimeout property is the number of seconds an upload is allowed to occur before ASP.NET closes, maxRequestLength refers to limiting the size of the uploaded file, and useFullyQualifiedRedirectUrl indicates whether the client-side redirect is fully qualified, or whether a relative redirect is sent to the client instead.

That's all done here, feel free to share a better way!


Recommended>>
1、Code Release DataJPA for SpringBoot Development with Kotlin
2、Ringing the bell Time is running out for cloud computing service companies as ecowar becomes the ultimate battle
3、Detailed commentary on the part of the main function for face recognition in opencv
4、Block 68 Mining Those Things
5、Big change at Coinbase Its going to be in bed with junk tokens

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号