mbtq

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1 前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

<!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 id="Head1" runat="server">
    <title>批量上传</title>
    <script src="jquery/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        var count = 1; //上传组件个数
        $(function () {
            //添加上传组件
            $("#btnAdd").click(function () {
                //                if ($("#DivUploads").find(":button").length >= 7) {
                //                    alert('最多只能添加八个上传组件!');
                //                    return;
                //                }
                var strHtml = '<span><input type="file" name="fileUpload" runat="server" />';
                strHtml += "<input type='button' onclick='delUploadBtn(" + count + ")' value='删除'/></span>";
                $("#DivUploads").append(strHtml);
                count++;
            });
        });
        //删除上传组件
        function delUploadBtn(index) {
            $("#DivUploads").find(":button").each(function () {
                var text = "" + $(this).attr("onclick");
                if (text.indexOf("delUploadBtn(" + index + ")") != -1) {
                    $(this).parent().remove();
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    &nbsp;&nbsp;
    <%-- <asp:LinkButton ID="btnAdd" runat="server">添加</asp:LinkButton>--%>
    <input type="button" id="btnAdd" value="添加" />
    <div id="DivUploads" style="border: 0px solid; width: 300px; height: auto;">
    </div>
    <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" />
    </form>
</body>
</html>


2 后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 上传处理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filepath = Request.Form["fileUpload"];

       //上传文件保存路径 
        string savePath = Server.MapPath("UploadFiles") + "\\";   

        //提供对客户端上载文件的访问
        HttpFileCollection uploadFiles = System.Web.HttpContext.Current.Request.Files;
        try
        {
            for (int i = 0; i < uploadFiles.Count; i++)
            {
                System.Web.HttpPostedFile postedFile = uploadFiles[i];
                string fileName = postedFile.FileName;//完整的路径
                fileName = System.IO.Path.GetFileName(postedFile.FileName); //获取到名称
                string fileExtension = System.IO.Path.GetExtension(fileName);//文件的扩展名称
                string type = fileName.Substring(fileName.LastIndexOf(".") + 1);    //类型 
                if (uploadFiles[i].ContentLength > 0)
                    uploadFiles[i].SaveAs(savePath + fileName);
            }
        }
        catch (System.Exception Ex)
        {
            Response.Write(Ex);
        }
    }
}

还是整个运行的效果图:

 

 

 

 

为了用着方便以及代码重用,可以新建一个客户端控件,加到客户端里面去

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uploadControl.ascx.cs" Inherits="Admin_userControl_uploadControl" %>
 <style type="text/css">
    #table_fileList{
        clear:left;
        border-top:1px solid #A2C1E0;
        border-left:1px solid #A2C1E0;
        border-spacing:0px;
    }
    #table_fileList td{
        border-right:1px solid #A2C1E0;
        border-bottom:1px solid #A2C1E0;
    }
    #table_fileList th{
        border-right:1px solid #A2C1E0;
        border-bottom:1px solid #A2C1E0;
    }
    </style>
    <script type="text/javascript">

        var count = 2; //上传组件个数
        $(function() {
            //添加上传组件 New method
            $("#btnAddUploadNew").click(function() {
                var fileName = GetUploadFileName();
                if (fileName == "") {
                    alert('上传文件不能为空!');
                    return;
                }
                else {
                    var fileCount = GetUploadFileCount();
                    if (!checkFile(fileName))//检查文件是否重复上传
                    {
                        return;
                    }
                    var Html = "<tr><td>" + fileName + "</td><td><img src='../Images/cross.png' alt='删除' onclick='delUploadBtn(" + count + ")'/></td></tr>";
                    $("#uploadBody").append(Html);

                    var strHtml = '<span><input type="file" name="fileUpload" runat="server" /><input type="text" value="' + count + '" style="display:none" /></span>';
                    $("#DivUploads").find(":file").each(function() {
                        $(this).css("display", "none");
                    });
                    $("#DivUploads").append(strHtml);
                    if (fileCount == 4) {
                        $("#DivUploads span:last-child").find(":file").attr("disabled", "disabled");
                    }
                    count++;
                }
            });

        });

        //删除上传组件
        function delUploadBtn(index) {
            //删除隐藏的上传控件
            $("#DivUploads").find(":text").each(function() {
                if ($(this).attr("value") == "" + (index - 1)) {
                    $(this).parent().remove();
                    return;
                }
            });
            //New method删除下方显示的上传文件列表
            $("#uploadBody tr td").find("img").each(function() {
                var text = ""+$(this).attr("onclick");
                if (text.indexOf(index) != -1) {
                    $(this).parent().parent().remove();
                }
            });
            $("#DivUploads span:last-child").find(":file").attr("disabled", ""); //上传控件恢复可用
        }


        //获取上传文件的数量
        function GetUploadFileCount() {
            var count = 0;
            $("#uploadBody tr").each(function() {
                count++;
            });
            return count;
        }

        //获取上传文件名
        function GetUploadFileName() {
            var fileName = "";
            $("#DivUploads").find(":file").each(function() {
                if ($(this).css("display") != "none") {
                    fileName = $(this).val();
                    return;
                }
            });
            return fileName;
        }
        //检查上传文件是否重复,以及扩展名是否符合要求
        function checkFile(fileName) {
            var flag = true;
            $("#uploadBody tr td").each(function() {
                if (fileName == $(this).text()) {
                    flag = false;
                    alert('上传文件中已经存在\'' + fileName + '\'!');
                    return;
                }
            });
            //文件类型判断
            var str = "jpg|jpeg|bmp|gif|doc|docx|xls|xlsx|txt";
            var fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1); //获取上传文件扩展名
            if (str.indexOf(fileExtName.toLowerCase()) == -1) {
                alert("只允许上传格式为jpg,jpeg,bmp,doc,docx,xls,xlsx,txt的文件。");
                flag = false;
            }
            return flag;
        }
       
    </script>
    
    <!--上传控件列表begin-->
    <div id="DivUploads" style="height:auto;float:left;width:250px;">
      <span>
      <input id="file_first" type="file" name="fileUpload" runat="server"/>
      <input type="text" value="1" style="display:none" />
      </span>
    </div><input id="btnAddUploadNew" type="button" value="添加" />
  <!--上传控件列表end-->
  <br/>
    <!--上传文件列表begin-->
    <table border="0" cellspacing="1" cellpadding="0" id="table_fileList" >
    <thead>
        <tr>
            <th style="width: 464px;" align="left">
                文件名</th>
            <th >
                删除</th>
        </tr>
    </thead>
    <tbody id="uploadBody">
    </tbody>
    </table>
  <!--上传文件列表end-->    

posted on 2012-11-11 14:03  mbtq  阅读(6155)  评论(0编辑  收藏  举报