天天看點

c# web fileUpload實作多檔案上傳

1) web.config

<system.web>
    <!---單個檔案最大隻能是20M如果大于20M就會出錯-->
    <httpRuntime maxRequestLength="20480"></httpRuntime>
           

2)前台代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUploadDemo._Default" %>
<!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>
    <style type="text/css">
         body{ font-size:12px;}
         body a{ cursor:pointer;}
    </style>
    <script language="javascript" type="text/javascript" src="js/jquery-1.4.2.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            var i = 2;
            $("#add").click(function() {
                if (i <= 8) {
                    var html = '<span>檔案' + i + ':</span><br/><input type="file" class="upload" runat="server" /><br /><br />';
                    $("#content").append(html);
                    i++;
                }
                else {
                    alert("最多能上傳8個檔案!");
                }
            });
        });
        function fileError(error) {//上傳檔案出錯
            alert(error);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="content">
    <asp:Button ID="btnUp" runat="server" Text="上傳" Width="90" οnclick="btnUp_Click" /><br /><br />
    <span>檔案1:</span><br/><input type="file" class="upload" runat="server" /><br /><br />
    </div>
    <br />
    <a id="add">添加更多附件 </a>
    </form>
</body>
</html>
           

3)背景代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
namespace FileUploadDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        private StringBuilder sb = new StringBuilder();//用來擷取上傳時出錯資訊 
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnUp_Click(object sender, EventArgs e)
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;//擷取上傳控件的個數
            if (haveFile(files))//存在上傳檔案
            {
                if (FindError(files))//上傳檔案不存在錯誤
                {
                    bool flag = false;
                    string dirPath = Server.MapPath(@"~/dir");//上傳檔案夾路徑
                    if (!Directory.Exists(dirPath))//不存在上傳檔案夾
                    {
                        Directory.CreateDirectory(dirPath);//建立檔案夾
                    }
                    for (int i = 0; i < files.Count; i++)//周遊上傳控件
                    {
                        string path = files[i].FileName;//上傳檔案路徑
                        string fileName = Path.GetFileName(path);//擷取檔案名
                        string savePath = dirPath + @"/" + fileName;//上傳檔案路徑
                        if (path != "")
                        {
                            try
                            {
                                files[i].SaveAs(savePath);
                                flag = false;
                            }
                            catch (Exception ex)
                            {
                                flag = true;
                            }
                        }
                    }
                    if (flag)//上傳檔案時出錯
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "uploadError", "alert('上傳檔案出錯!')", true);
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "uploadSuccess", "alert('上傳檔案成功!')", true);
                    }
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "fileError", string.Format("fileError('{0}')", sb.ToString()), true);
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "haveNoFile", "alert('請選擇上傳檔案!')", true);
            }
        }
        /// <summary>
        /// 判斷是否有上傳檔案
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        private bool haveFile(HttpFileCollection files)
        {
            bool flag = false;
            for (int i = 0; i < files.Count; i++)
            {
                string path = files[i].FileName;//上傳檔案路徑
                if (path != "") { flag = true; break; }//存在上傳檔案
            }
            return flag;
        }
        /// <summary>
        ///  判斷上傳檔案是否有錯
        /// 上傳檔案有錯return false
        /// 上傳檔案沒有錯return true
        /// </summary>
        /// <param name="files">上傳控件</param>
        /// <returns></returns>
        private bool FindError(HttpFileCollection files)
        {
            bool flag = false;
            for (int i = 0; i < files.Count; i++)//周遊上傳控件
            {
                string path = files[i].FileName;//上傳檔案路徑
                if (path != "")//上傳控件中存在上傳檔案
                {
                    string fileName = Path.GetFileName(path);//擷取上傳檔案名
                    string fex = Path.GetExtension(path);//擷取上傳檔案的字尾名
                    if (files[i].ContentLength / 4096 > 1024)//上傳檔案大于4M
                    {
                        sb.Append(fileName + "的大小超過4M!");
                        break;
                    }
                    if (fex == ".exe" || fex == ".EXE") //上傳檔案是exe檔案
                    {
                        sb.Append(fileName + "的格式不正确!");
                        break;
                    }
                }
            }
            if (sb.ToString() == "") { flag = true; }//上傳檔案沒有錯誤
            return flag;
        }
    }
}
           

繼續閱讀