2014-07-23 利用ASP.NET自带控件实现单文件上传与下载
生活随笔
收集整理的這篇文章主要介紹了
2014-07-23 利用ASP.NET自带控件实现单文件上传与下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
效果圖
上傳文件頁面:
下載文件頁面:
?
1、母版頁site.Master
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="upAndDown.SiteMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> <asp:ContentPlaceHolder ID="HeadContent" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form runat="server"> <div class="page"> <div class="header"> <div class="title"> <h1> 我的 ASP.NET 應用程序之-多文件上傳+超大附件上傳 </h1> </div> <div class="loginDisplay"> -by Leon</div> <div class="clear hideSkiplink"> <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"? EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal"? > <Items> <asp:MenuItem NavigateUrl="~/Default.aspx" Text="上傳"/> <asp:MenuItem NavigateUrl="~/Download.aspx" Text="下載"/> </Items> </asp:Menu> </div> </div> <div class="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server"/> </div> <div class="clear"> </div> </div> <div class="footer"> </div> </form> </body> </html>
2、Default.aspx 上傳頁面
<%@ Page Title="文件上傳與下載" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="upAndDown._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> 上傳文件到服務器</h2> <h2> <asp:FileUpload ID="FileUpload1" runat="server" /> </h2> <p> <asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="上傳" style="margin-left:170px;" /> </p> </asp:Content>
3、Default.aspx.cs?
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace upAndDown { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public Boolean UpLoad(string path, FileUpload fileupload)? { bool fileOK = false; if(fileupload.HasFile) { string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower(); //上傳文件的格式 string[] allowedException = {".xls",".doc",".mp3",".rar",".zip",".vsd",".txt",".jpg",".gif",".bmp" ,".png",".swf",".avi",".mp3",".rm",".wma",".wmv",".exe"}; for (int i = 0; i < allowedException.Length;i++ )? { if (fileException == allowedException[i])? fileOK = true; ?//返回成功標識 } } if (fileOK) ? ? //判斷上傳的文件是否在指定的格式范圍之內 { //判斷文件是否存在,如不存在則創建路徑 if (System.IO.Directory.Exists(path)) { //該目錄存在,則將上傳的文件保存在該目錄當中 } else { System.IO.Directory.CreateDirectory(path); ? ? ?//創建文件路徑 } fileupload.SaveAs(path + "\\" + fileupload.FileName.Trim().Replace(" ","")); ? //去掉文件名字符空格,執行文件上傳操作 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件上傳成功!')</script>"); } else? { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('不支持此格式文件上傳!')</script>"); } return fileOK; } protected void Button1_Click(object sender, EventArgs e) { string FilePath = ""; //是否有上傳文件 if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "") { if (FileUpload1.PostedFile.ContentLength <= 0) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('上傳文件為空文件,請重新選擇!')</script>");? return; } else {? if (this.FileUpload1.HasFile) { if (FileUpload1.PostedFile.ContentLength > 524288000) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "<script>alert('上傳文件過大!')</script>");? return; } else { FilePath = Server.MapPath("/Images"); //設置服務器路徑 } UpLoad(FilePath, this.FileUpload1);//調用UpLoad()函數上傳文件 } } } //如果上傳文件錯誤,則返回操作 else? { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件為空,請先選擇要上傳的文件!')</script>");? return; } } } }
4、Download.aspx 下載頁面
<%@ Page Title="文件下載" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Download.aspx.cs" Inherits="upAndDown.Download" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2 style="font-size: xx-large"> 從服務器上下載文件</h2> <p> <asp:ListBox ID="ListBox1" runat="server" Height="249px" ?Width="541px"> </asp:ListBox> </p> <embed style="filter: xray()" src="Images/GEM.mp3" width="188" height="68" type="audio/mp3" loop="true" showstatusbar="true" autostart="true"/> <p> <asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Size="Small" Font-Strikeout="False" Text="下載" οnclick="Button1_Click" /> </p> </asp:Content> ?
5、Download.aspx.cs ?
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace upAndDown { public partial class Download : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) {? //頁面加載時,獲取下載文件的存放目錄 string strfilepath = Server.MapPath("~/Images/"); //創建目錄對象 DirectoryInfo dir = new DirectoryInfo(strfilepath); //獲得該目錄下的所有文件 FileSystemInfo[] files = dir.GetFileSystemInfos(); //講遍歷的文件名稱顯示在ListBox控件中 ListItem items; foreach (FileSystemInfo infofiles in files)? { items = new ListItem(); ? ? ? ?//聲明一個ListItem對象 items.Text = infofiles.Name; items.Value = infofiles.FullName; ListBox1.Items.Add(items); ? ? //向ListBox控件中添加數據信息 } } } //<summary> //文件下載函數 //</summary> //author Leon //<param name="fileURL">要下載文件所在的路徑</param> protected Boolean DownLoad(string fileURL) { Boolean Dok = false; try { string FullPathURL = Server.MapPath(fileURL);//獲取文件下載路徑 System.IO.FileInfo file = new System.IO.FileInfo(FullPathURL); if (file.Exists) ? ? ? ?//判斷要下載的文件是否存在 { Response.Clear(); ? ? ? //清空response對象中的內容 //*修改前的做法 Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name); //*修改后的做法 Response.AddHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name)); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(FullPathURL); ? ? ?//通過對Response對象執行下載文件的操作 Response.End(); ? ? //結束Response對象 Response.Flush(); ? ? ? //刷新Response對象 Response.Clear(); ? ? ? //清空response對象中的內容 Dok = true; } else { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"success","<script>alert(' 文件不存在!')</script>"); } } catch (Exception) { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('文件不存在!')</script>"); } return Dok; } protected void Button1_Click(object sender, EventArgs e) { //獲取下載文件的路徑 string downfiles; try { downfiles = "Images/" + ListBox1.SelectedItem.Text; DownLoad(downfiles); } catch (Exception) { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('選擇文件為空,請先選擇要下載的文件!')</script>"); } } } } ?
注:ASP.NET框架默認最大上傳文件為4M,如果要修改框架默認最大上傳文件大小,?需要到C:\Windows \Microsoft.NET\Framework\v4.0.30319\Config文件夾中修改machine.config文件, 在<system.web> 標簽中加入或修改<httpRuntime maxRequestLength="4096000"/>的值。
上傳文件頁面:
下載文件頁面:
?
1、母版頁site.Master
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="upAndDown.SiteMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> <asp:ContentPlaceHolder ID="HeadContent" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form runat="server"> <div class="page"> <div class="header"> <div class="title"> <h1> 我的 ASP.NET 應用程序之-多文件上傳+超大附件上傳 </h1> </div> <div class="loginDisplay"> -by Leon</div> <div class="clear hideSkiplink"> <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"? EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal"? > <Items> <asp:MenuItem NavigateUrl="~/Default.aspx" Text="上傳"/> <asp:MenuItem NavigateUrl="~/Download.aspx" Text="下載"/> </Items> </asp:Menu> </div> </div> <div class="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server"/> </div> <div class="clear"> </div> </div> <div class="footer"> </div> </form> </body> </html>
2、Default.aspx 上傳頁面
<%@ Page Title="文件上傳與下載" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="upAndDown._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> 上傳文件到服務器</h2> <h2> <asp:FileUpload ID="FileUpload1" runat="server" /> </h2> <p> <asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="上傳" style="margin-left:170px;" /> </p> </asp:Content>
3、Default.aspx.cs?
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace upAndDown { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public Boolean UpLoad(string path, FileUpload fileupload)? { bool fileOK = false; if(fileupload.HasFile) { string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower(); //上傳文件的格式 string[] allowedException = {".xls",".doc",".mp3",".rar",".zip",".vsd",".txt",".jpg",".gif",".bmp" ,".png",".swf",".avi",".mp3",".rm",".wma",".wmv",".exe"}; for (int i = 0; i < allowedException.Length;i++ )? { if (fileException == allowedException[i])? fileOK = true; ?//返回成功標識 } } if (fileOK) ? ? //判斷上傳的文件是否在指定的格式范圍之內 { //判斷文件是否存在,如不存在則創建路徑 if (System.IO.Directory.Exists(path)) { //該目錄存在,則將上傳的文件保存在該目錄當中 } else { System.IO.Directory.CreateDirectory(path); ? ? ?//創建文件路徑 } fileupload.SaveAs(path + "\\" + fileupload.FileName.Trim().Replace(" ","")); ? //去掉文件名字符空格,執行文件上傳操作 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件上傳成功!')</script>"); } else? { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('不支持此格式文件上傳!')</script>"); } return fileOK; } protected void Button1_Click(object sender, EventArgs e) { string FilePath = ""; //是否有上傳文件 if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "") { if (FileUpload1.PostedFile.ContentLength <= 0) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('上傳文件為空文件,請重新選擇!')</script>");? return; } else {? if (this.FileUpload1.HasFile) { if (FileUpload1.PostedFile.ContentLength > 524288000) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "<script>alert('上傳文件過大!')</script>");? return; } else { FilePath = Server.MapPath("/Images"); //設置服務器路徑 } UpLoad(FilePath, this.FileUpload1);//調用UpLoad()函數上傳文件 } } } //如果上傳文件錯誤,則返回操作 else? { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件為空,請先選擇要上傳的文件!')</script>");? return; } } } }
4、Download.aspx 下載頁面
<%@ Page Title="文件下載" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Download.aspx.cs" Inherits="upAndDown.Download" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2 style="font-size: xx-large"> 從服務器上下載文件</h2> <p> <asp:ListBox ID="ListBox1" runat="server" Height="249px" ?Width="541px"> </asp:ListBox> </p> <embed style="filter: xray()" src="Images/GEM.mp3" width="188" height="68" type="audio/mp3" loop="true" showstatusbar="true" autostart="true"/> <p> <asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Size="Small" Font-Strikeout="False" Text="下載" οnclick="Button1_Click" /> </p> </asp:Content> ?
5、Download.aspx.cs ?
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace upAndDown { public partial class Download : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) {? //頁面加載時,獲取下載文件的存放目錄 string strfilepath = Server.MapPath("~/Images/"); //創建目錄對象 DirectoryInfo dir = new DirectoryInfo(strfilepath); //獲得該目錄下的所有文件 FileSystemInfo[] files = dir.GetFileSystemInfos(); //講遍歷的文件名稱顯示在ListBox控件中 ListItem items; foreach (FileSystemInfo infofiles in files)? { items = new ListItem(); ? ? ? ?//聲明一個ListItem對象 items.Text = infofiles.Name; items.Value = infofiles.FullName; ListBox1.Items.Add(items); ? ? //向ListBox控件中添加數據信息 } } } //<summary> //文件下載函數 //</summary> //author Leon //<param name="fileURL">要下載文件所在的路徑</param> protected Boolean DownLoad(string fileURL) { Boolean Dok = false; try { string FullPathURL = Server.MapPath(fileURL);//獲取文件下載路徑 System.IO.FileInfo file = new System.IO.FileInfo(FullPathURL); if (file.Exists) ? ? ? ?//判斷要下載的文件是否存在 { Response.Clear(); ? ? ? //清空response對象中的內容 //*修改前的做法 Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name); //*修改后的做法 Response.AddHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name)); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(FullPathURL); ? ? ?//通過對Response對象執行下載文件的操作 Response.End(); ? ? //結束Response對象 Response.Flush(); ? ? ? //刷新Response對象 Response.Clear(); ? ? ? //清空response對象中的內容 Dok = true; } else { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"success","<script>alert(' 文件不存在!')</script>"); } } catch (Exception) { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('文件不存在!')</script>"); } return Dok; } protected void Button1_Click(object sender, EventArgs e) { //獲取下載文件的路徑 string downfiles; try { downfiles = "Images/" + ListBox1.SelectedItem.Text; DownLoad(downfiles); } catch (Exception) { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('選擇文件為空,請先選擇要下載的文件!')</script>"); } } } } ?
注:ASP.NET框架默認最大上傳文件為4M,如果要修改框架默認最大上傳文件大小,?需要到C:\Windows \Microsoft.NET\Framework\v4.0.30319\Config文件夾中修改machine.config文件, 在<system.web> 標簽中加入或修改<httpRuntime maxRequestLength="4096000"/>的值。
轉載于:https://www.cnblogs.com/leon719/p/3862568.html
總結
以上是生活随笔為你收集整理的2014-07-23 利用ASP.NET自带控件实现单文件上传与下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cocos2d-x和时间有关的代码
- 下一篇: SSL F5