1. 程式人生 > >ASP.NET檔案上傳和下載

ASP.NET檔案上傳和下載

aspx頁面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="上傳和下載檔案.aspx.cs" Inherits="上傳和下載檔案" %>

<!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">
    <asp:FileUpload ID="homeworkFile" runat="server" />
    <asp:Button ID="btnAdd" runat="server" Text="上傳"  OnClick="btnAdd_Click"/></br>
    <asp:Button ID="btndownfile" runat="server" Text="下載方法一:TransmitFile" 
        onclick="btndownfile_Click" /></br>
       <asp:Button ID="btndownfilebyWriteFile" runat="server" 
        Text="下載方法二:WriteFile" onclick="btndownfilebyWriteFile_Click" /></br>
        <asp:Button ID="btndownfilebyWriteFile2" runat="server" 
        Text="下載方法三:WriteFile分塊" onclick="btndownfilebyWriteFile2_Click" /><br />
        <asp:Button ID="btndownfilebystream" runat="server" Text="下載方法四:流方式下載" 
        onclick="btndownfilebystream_Click" />
    </form>
</body>
</html>

aspx後臺程式碼:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class 上傳和下載檔案 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //檔案原名
        string fileName = Path.GetFileName(this.homeworkFile.FileName);
        //檔案新名字=檔案原名+當前時間
        string newFileName = fileName.Substring(0, fileName.IndexOf('.')) + DateTime.Now.ToString("yyyyMMddhhmmss");
        //給檔名加字尾名
        newFileName += fileName.Substring(fileName.IndexOf('.'), fileName.Length - fileName.IndexOf('.'));
        //獲得檔案儲存的路徑名
        string Url = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"] + @"\" + newFileName;
        //驗證檔案大小
        if (this.IsFileSizeLessMax())
        {  //驗證檔案的型別
            if (this.isTypeOk(Url))
            {
                //驗證檔案儲存的路徑是否存在
                string pathStr = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"];
                if (!Directory.Exists(pathStr))  //如果不存在路徑
                {
                    Directory.CreateDirectory(pathStr);    //建立路徑
                }
                if (!Url.Equals(""))    //如果有上傳檔案
                {
                    FileUpload fileUpLoad = new FileUpload();
                    //1.存放檔案 
                    // fileUpLoad.SaveAs(Url);
                    homeworkFile.PostedFile.SaveAs(Url);
                }
            }
        }
    }
    /// <summary>
    /// 驗證上傳檔案是否超過規定的最大值
    /// </summary>
    /// <returns></returns>
    private bool IsFileSizeLessMax()
    {
        //返回值
        bool result = false;
        if (this.homeworkFile.HasFile)    //如果上傳了檔案
        {
            //獲取上傳檔案的允許最大值
            long fileMaxSize = 1024 * 1024;
            try
            {
                fileMaxSize *= int.Parse(ConfigurationManager.AppSettings["FileUploadMaxSize"].Substring(0, ConfigurationManager.AppSettings["FileUploadMaxSize"].Length - 1));
            }
            catch (Exception ex)
            {
                //this.WriteException("UserPotal:Homework", ex);
            }
            if (this.homeworkFile.PostedFile.ContentLength > int.Parse(fileMaxSize.ToString()))    //如果檔案大小超過規定的最大值
            {
                //this.ShowMessage("檔案超過規定大小。");
            }
            else
            {
                result = true;
            }
        }
        else    //如果沒有上傳的檔案
        {
            result = true;
        }
        return result;
    }

    /// <summary>
    /// 驗證檔案型別的方法
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    private bool isTypeOk(string fileName)
    {
        //返回結果
        bool endResult = false;
        //驗證結果
        int result = 0;
        if (!fileName.Equals(""))    //如果有上傳檔案
        {
            //允許的檔案型別
            string[] fileType = null;
            try
            {
                fileType = ConfigurationManager.AppSettings["FileType"].Split(',');
            }
            catch (Exception ex)
            {
                //this.ShowMessage("獲取配置檔案資訊出錯");
                //this.WriteException("AdminProtal:Homework", ex);
            }
            fileName = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
            for (int i = 0; i < fileType.Length; i++)
            {
                if (fileType[i].Equals(fileName))    //如果是合法檔案型別
                {
                    result++;
                }
            }
            if (result > 0)
            {
                endResult = true;
            }
        }
        else    //如果沒有上傳檔案
        {
            endResult = true;
        }
        return endResult;
    }
    //下載方法一
    protected void btndownfile_Click(object sender, EventArgs e)
    {
        /* 微軟為Response物件提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite 下載超過400mb的檔案時導致Aspnet_wp.exe程序回收而無法成功下載的問題。 程式碼如下: */

        Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader("Content-Disposition", "attachment;filename=DBintegrate20120521030107.txt");
        string filename = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt");
        Response.TransmitFile(filename);
    }
    //下載方法二
    protected void btndownfilebyWriteFile_Click(object sender, EventArgs e)
    {
        /* using System.IO; */
        string fileName = "DBintegrate20120521030107.txt";//客戶端儲存的檔名 
        string filePath = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt");//路徑 
        FileInfo fileInfo = new FileInfo(filePath);
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.AddHeader("Content-Transfer-Encoding", "binary");
        Response.ContentType = "application/octet-stream";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        Response.WriteFile(fileInfo.FullName);
        Response.Flush();
        Response.End();

    }
    //下載方法三
    protected void btndownfilebyWriteFile2_Click(object sender, EventArgs e)
    {
        string fileName = "前臺老師和學生介面對比20120521034329.rar";//客戶端儲存的檔名 
        string filePath = Server.MapPath("BJNetwork/Data/前臺老師和學生介面對比20120521034329.rar");//路徑 
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
        if (fileInfo.Exists == true)
        {
            const long ChunkSize = 102400;//100K 每次讀取檔案,只讀取100K,這樣可以緩解伺服器的壓力 
            byte[] buffer = new byte[ChunkSize];
            Response.Clear();
            System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
            long dataLengthToRead = iStream.Length;//獲取下載的檔案總大小 
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
            while (dataLengthToRead > 0 && Response.IsClientConnected)
            {
                int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); 
                Response.Flush();
                dataLengthToRead = dataLengthToRead - lengthRead;
            }
            Response.Close();
        }

    }
    //下載方法四
    protected void btndownfilebystream_Click(object sender, EventArgs e)
    {
        string fileName = "前臺老師和學生介面對比20120521034329.rar";//客戶端儲存的檔名 
        string filePath = Server.MapPath("BJNetwork/Data/前臺老師和學生介面對比20120521034329.rar");//路徑 //以字元流的形式下載檔案 
        FileStream fs = new FileStream(filePath, FileMode.Open);
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();
        Response.ContentType = "application/octet-stream";
        //通知瀏覽器下載檔案而不是開啟 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
}

web配置檔案:

<appSettings>
     <!--上傳檔案的路徑-->
    <add key="ResoursePath" value="D:\IbeaconShow\BJNetwork"/>
    <add key="RESHomeworkContentPath" value="\Data"/>
    <!--可上傳檔案的大小-->
    <add key="FileUploadMaxSize" value="20M"/>
    <!--可上傳檔案型別 -->
    <add key="FileType" value=".zip,.txt,.doc,.rar,.xls,.rtf,.xlsx,.docx,.png"/>
  </appSettings>

 <system.web>
     <!--修改asp.net預設上傳檔案的大小-->
    <httpRuntime executionTimeout="300" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false"/>

 </system.web>

IIS中上傳大小的修改

1、首先要到程序中把IIS服務關了,即把inetinfo.exe程序關了,不然裡面的檔案不給你更改的喲~~~
    2、在系統目錄中找到:windows/system32/inesrv/metabase.xml”檔案,找個文字編輯器開啟他,我都用EditPuls(這傢伙不錯,帶字型色彩的),Ctrl+F 找到AspMaxRequestEntityAllowed="204800"這一項,這就是iis上傳檔案的預設大小了,預設為204800Byte,也就是200KB,將它改為你需要的大小就可以了!