asp.net 檔案上傳和下載管理原始碼

暖楓無敵發表於2014-11-08

    利用asp.net進行檔案上傳和下載時非常常用的功能,現做整理,將原始碼上傳,提供給初學者參考,以下程式碼中的樣式檔案就不上傳了,下載者請將樣式去掉。

效果圖如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadManager.aspx.cs"
    Inherits="NewsManagement_FileUploadManager" %>

<!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>
    <link href="../themes/common.css" rel="stylesheet" type="text/css" />
    <link href="../themes/reset.css" rel="stylesheet" type="text/css" />
    <link href="../themes/modules.css" rel="stylesheet" type="text/css" />
    <link href="../themes/fix.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div class="right">
        <table cellpadding="1" cellspacing="1" class="tablesingle" width="100%" style=" height:500px;">
            <tr>
                <td colspan="3">
                    <asp:Label ID="lab_FolderInfo" runat="server" Font-Size="Medium"></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="tablesingletdlable"  valign="top" align="center">
                    允許上傳檔案的型別:
                    <asp:BulletedList ID="bl_FileTypeLimit" runat="server">
                    </asp:BulletedList>
                    允許上傳單個檔案的大小:
                    <asp:Label ID="lab_FileSizeLimit" runat="server" Text=""></asp:Label>
                </td>
                <td class="tablesingletdlable" align="left">
                    <asp:FileUpload ID="FileUpload" runat="server" Width="300px" /><br /><br />
                    <asp:Button ID="btn_Upload" runat="server" CssClass="button-add-new" Style="height: 26px;
                        width: 64px; border: 0px;" Text="上傳檔案" OnClick="btn_Upload_Click" />
                </td>
                <td class="tablesingletdlable">
                    <table cellpadding="1" cellspacing="1" class="tablesingle" width="100%">
                        <tr>
                            <td>
                                <!--啟用了AutoPostBack-->
                                <asp:ListBox ID="lb_FileList" runat="server" AutoPostBack="True" Width="300px" Height="400px"
                                    OnSelectedIndexChanged="lb_FileList_SelectedIndexChanged"></asp:ListBox>
                            </td>
                            <td valign="top">
                                <asp:Label ID="lab_FileDescription" runat="server" Text=""></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:Button ID="btn_Download" runat="server" CssClass="button-add-new" Style="height: 26px;
            width: 64px; border: 0px;" Text="下載檔案" OnClick="btn_Download_Click" /> 
                                <!--在刪除前給予確認-->
                                <asp:Button ID="btn_Delete" runat="server" CssClass="button-add-new" Style="height: 26px;
            width: 64px; border: 0px;" Text="刪除檔案" OnClientClick="return confirm('確定刪除檔案嗎?')"
                                    OnClick="btn_Delete_Click" /><br />
                                <asp:TextBox ID="tb_FileNewName" runat="server" Width="300px"></asp:TextBox> 
                                <asp:Button ID="btn_Rename" runat="server" CssClass="button-4" Style="height: 26px;
            width: 110px; border: 0px;" Text="對檔案重新命名" OnClick="btn_Rename_Click" /> 
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Configuration;
using SYIT.Tools.DotNetUI;

public partial class NewsManagement_FileUploadManager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //防止PostBack後列表資訊重複新增
        if (!IsPostBack)
        {
            //初始化資料夾資訊
            InitFolderInfo();
            //初始化上傳限制資訊
            InitUploadLimit();
            //初始化檔案列表
            InitFileList();
        }
    }

    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        //判斷使用者是否選擇了檔案
        if (FileUpload.HasFile)
        {
            //呼叫自定義方法判斷檔案型別是否符合要求
            if (IsAllowableFileType())
            {
                //呼叫自定義方法判斷檔案大小是否符合要求
                if (IsAllowableFileSize())
                {
                    //從config中讀取檔案上傳路徑
                    string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
                    //從UploadFile中讀取檔名
                    string strFileName = FileUpload.FileName;
                    //組合成物理路徑
                    string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
                    //儲存檔案
                    FileUpload.SaveAs(strFilePhysicalPath);
                    //更新檔案列表框控制元件
                    lb_FileList.Items.Add(strFileName);
                    //更新資料夾資訊
                    InitFolderInfo();
                    //呼叫自定義方法顯示提示
                    ShowMsgHelper.AlertMsg2("檔案成功上傳!");
                    //ShowMessageBox("檔案成功上傳");
                }
                else
                {
                    //呼叫自定義方法顯示提示
                    
                    ShowMessageBox("檔案大小不符合要求,請參看上傳限制");
                }
            }
            else
            {
                //呼叫自定義方法顯示提示
               
                ShowMessageBox("檔案型別不符合要求,請參看上傳限制");
            }
        }
        else
        {
            //呼叫自定義方法顯示提示
           
            ShowMessageBox("請選擇一個檔案");
        }
    }

    protected void btn_Download_Click(object sender, EventArgs e)
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //從列表框控制元件中讀取選擇的檔名
        string strFileName = lb_FileList.SelectedValue;
        //組合成物理路徑
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //清空輸出流
        Response.Clear();
        //在HTTP頭中加入檔名資訊
        Response.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
        //定義輸出流MIME型別為
        Response.ContentType = "application/octet-stream";
        //從磁碟讀取檔案流
        System.IO.FileStream fs = System.IO.File.OpenRead(strFilePhysicalPath);
        //定義緩衝區大小
        byte[] buffer = new byte[102400];
        //第一次讀取
        int i = fs.Read(buffer, 0, buffer.Length);
        //如果讀取的位元組大於0,則使用BinaryWrite()不斷向客戶端輸出檔案流
        while (i > 0)
        {
            Response.BinaryWrite(buffer);
            i = fs.Read(buffer, 0, buffer.Length);
        }
        //關閉磁碟檔案流
        fs.Close();
        //關閉輸出流
        Response.End();
    }

    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //從列表框控制元件中讀取選擇的檔名
        string strFileName = lb_FileList.SelectedValue;
        //組合成物理路徑
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //刪除檔案
        System.IO.File.Delete(strFilePhysicalPath);
        //更新檔案列表框控制元件
        lb_FileList.Items.Remove(lb_FileList.Items.FindByText(strFileName));
        //更新資料夾資訊
        InitFolderInfo();
        //更新檔案描述資訊
        tb_FileNewName.Text = "";
        //更新重新命名文字框
        lab_FileDescription.Text = "";
        //呼叫自定義方法顯示提示
      
        ShowMessageBox("檔案成功刪除");
    }

    protected void btn_Rename_Click(object sender, EventArgs e)
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //從列表框控制元件中讀取選擇的檔名
        string strFileName = lb_FileList.SelectedValue;
        //從重新命名文字框中讀取新檔名
        string strFileNewName = tb_FileNewName.Text;
        //組合成物理路徑
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //組合成物理路徑
        string strFileNewPhysicalPath = Server.MapPath(strFileUploadPath + strFileNewName);
        //檔案重新命名
        System.IO.File.Move(strFilePhysicalPath, strFileNewPhysicalPath);
        //找到檔案列表框控制元件中的匹配項
        ListItem li = lb_FileList.Items.FindByText(strFileName);
        //修改文字
        li.Text = strFileNewName;
        //修改值
        li.Value = strFileNewName;
        //呼叫自定義方法顯示提示
       
        ShowMessageBox("檔案成功重新命名");
    }

    protected void lb_FileList_SelectedIndexChanged(object sender, EventArgs e)
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //從列表框控制元件中讀取選擇的檔名
        string strFileName = lb_FileList.SelectedValue;
        //組合成物理路徑
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //根據物理路徑例項化檔案資訊類
        FileInfo fi = new FileInfo(strFilePhysicalPath);
        //獲得檔案大小和建立時間並賦值給標籤
        lab_FileDescription.Text = string.Format("檔案大小:{0} 位元組<br><br>上傳時間:{1}<br>", fi.Length, fi.CreationTime);
        //把檔名賦值給重新命名文字框
        tb_FileNewName.Text = strFileName;
    }

    private void InitFolderInfo()
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //判斷上傳資料夾是否存在
        if (!Directory.Exists(Server.MapPath(strFileUploadPath)))
            Directory.CreateDirectory(Server.MapPath(strFileUploadPath));
        //組合成物理路徑
        string strFilePath = Server.MapPath(strFileUploadPath);
        //從config中讀取資料夾容量限制
        double iFolderSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FolderSizeLimit"]);
        //宣告表示資料夾已用空間的變數並賦初始值
        double iFolderCurrentSize = 0;
        //獲取資料夾中所有檔案
        FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
        //累加檔案大小獲得已用空間值
        foreach (FileInfo fi in arrFiles)
            iFolderCurrentSize += Convert.ToInt32(fi.Length / 1024);
        //把資料夾容量和已用空間資訊賦值給標籤
        lab_FolderInfo.Text = string.Format("資料夾容量限制:{0} M 已用空間:{1:f2} M", iFolderSizeLimit / 1024, iFolderCurrentSize / 1024);
    }

    private void InitUploadLimit()
    {
        //從config中讀取上傳檔案型別限制並根據逗號分割成字串陣列
        string[] arrFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString().Split(',');
        //從config中讀取上傳檔案大小限制
        double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);
        //遍歷字串陣列把所有項加入專案編號控制元件
        for (int i = 0; i < arrFileTypeLimit.Length; i++)
            bl_FileTypeLimit.Items.Add(arrFileTypeLimit[i].ToString());
        //把檔案大小限制賦值給標籤
        lab_FileSizeLimit.Text = string.Format("{0:f2} M", iFileSizeLimit / 1024);
    }

    private void InitFileList()
    {
        //從config中讀取檔案上傳路徑
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //組合成物理路徑
        string strFilePath = Server.MapPath(strFileUploadPath);
        //讀取資料夾下所有檔案
        FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
        //把檔名逐一新增到列表框控制元件控制元件
        foreach (FileInfo fi in arrFiles)
            lb_FileList.Items.Add(fi.Name);
    }

    private bool IsAllowableFileSize()
    {
        //從config中讀取上傳檔案大小限制
        double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
        //檔案大小是否超出了大小限制?
        if (iFileSizeLimit > FileUpload.PostedFile.ContentLength)
            return true;
        else
            return false;
    }

    private bool IsAllowableFileType()
    {
        //從config中讀取上傳檔案型別限制
        string strFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString();
        //當前副檔名是否能在這個字串中找到?
        if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUpload.FileName).ToLower()) > -1)
            return true;
        else
            return false;
    }

    private void ShowMessageBox(string strMessaage)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", string.Format("<script>alert('{0}')</script>", strMessaage));
    }
}

===========================================================================

如果覺得對您有幫助,微信掃一掃支援一下:


相關文章