asp.net+JQuery实现文件批量上传!

做系统的时候难免会遇到需要批量上传这样的需求,之前一直没有做过,今天经理给了这个需求并简单讲了一下思路,花了点时间把它给做出来了,细想起来还是比较简单的。

思路:用JQuery来实现动态的添加或者删除多个上传控件(如<input type="file" name="fileUpload" runat="server" />),选择好上传的文件后,就可以一次性提交,避免了一个一个上传的麻烦。

下面是自己整的一个简单的demo

js部分的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="multiUpload.aspx.cs" Inherits="multiUpload" %>
<!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>
    <script src="JS/jquery-1.4.4.min.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' οnclick='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" />
    <input type="button" id="btnAdd" value="添加" />
    <div id="DivUploads" style="border:1px solid;width:300px;height:auto;">
    </div>
    <asp:Button ID="btnUpload" runat="server" Text="上传" οnclick="btnUpload_Click" />
    </form>
</body>
</html>

asp.net的后台代码:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class multiUpload : 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 = Request.Files;
        for (int i = 0; i < uploadFiles.Count; i++)
        { 
            if (uploadFiles[i].FileName != "")
            {
                uploadFiles[i].SaveAs(savePath + uploadFiles[i].FileName);
            }
        }           
    }
}

还是整个运行的效果图:

 

 

 

 

 

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

<%@ 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='删除' οnclick='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-->     

 

 

昨天为了回答百度知道上的问题,又用jquery写了一个可以预览的图片批量上传,记在这里(在IE8和Firefox4.0上测试通过)。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
   
<script type="text/javascript">  
//全局变量
var FileCount=0;//上传文件总数
 //添加上传文件按钮
 function addFile(obj)
 {
  var filePath=$(obj).prev().val();
  var FireFoxFileName="";
  //FireFox文件的路径需要特殊处理
  if(window.navigator.userAgent.indexOf("Firefox")!=-1)
  {
     FireFoxFileName=filePath;
     filePath=$(obj).prev()[0].files.item(0).getAsDataURL();
  }
  if(!checkFile(filePath,FireFoxFileName))
  {
    $(obj).prev().val("");
    return;
  }
  if(filePath.length==0)
  {
    alert("请选择上传文件");
   return false;
  }
   FileCount++;
   //添加上传按钮
   var html='<span>';
       html+='<input id="f'+FileCount+'" name="'+FileCount+'" type="file"/>&nbsp;';
       html+='<input type="button" value="添加" οnclick="addFile(this)"/>';
       html+='</span>';
   $("#fil").append(html);
   //添加图片预览
   html='<li>';
   html+='<img id="img'+(FileCount-1)+'" src="'+filePath+'" width="100" height="100" style="cursor:pointer;" alt="暂无预览" />';
   html+='<br/>';
   html+='<a href="#" name="img'+(FileCount-1)+'" οnclick="DelImg(this)">删除</a>';
   html+='</li>';
   $("#ImgList").append(html);
 }
 //删除上传文件(file以及img)
 function DelImg(obj)
 {
     var ID=$(obj).attr("name");
  ID=ID.substr(3,ID.length-3);
  $("#f"+ID).parent().remove();
  $(obj).parent().remove();
  return false;
 }
  //检查上传文件是否重复,以及扩展名是否符合要求
function checkFile(fileName,FireFoxFileName)
{
 var flag=true;
 $("#ImgList").find(":img").each(function(){
  if(fileName==$(this).attr("src"))
  {
  flag=false;
  if(FireFoxFileName!='')
  {
   alert('上传文件中已经存在\''+FireFoxFileName+'\'!');
  }
  else
  {
   alert('上传文件中已经存在\''+fileName+'\'!');
  }
  return;
  }
 });
 //文件类型判断
 var str="jpg|jpeg|bmp|gif|doc|docx|xls|xlsx|txt";
 var fileExtName=fileName.substring(fileName.indexOf(".")+1);//获取上传文件扩展名
 if(FireFoxFileName!='')//fireFox单独处理
 {
  fileExtName=FireFoxFileName.substring(FireFoxFileName.indexOf(".")+1);
 }
 //alert(fileExtName);
 if(str.indexOf(fileExtName.toLowerCase())==-1)
 {
   alert("只允许上传格式为jpg,jpeg,bmp,doc,docx,xls,xlsx,txt的文件。");
 flag=false;
 }
 return flag;
}
</script>   
<style type="text/css">   
  .fil
  {   
    width:300px;
  }
  .fieldset_img
  {
  border:1px solid blue;
  width:550px;
  height:180px;
  text-align:left;

  }
  .fieldset_img img
  {
     border:1px solid #ccc;
  padding:2px;
  margin-left:5px;
  }
  #ImgList li 
  {
     text-align:center;
     list-style:none;
  display:block;
  float:left;
  margin-left:5px;
  }
</style>   
</head>   
<body>   
<p>上传预览图片:<br>
<div id="fil" class="fil">
  <span>
   <input id="f0" name="f0" type="file"/>
   <input type="button" value="添加" οnclick="addFile(this)"/>
  </span>
</div> 
</p>
<div id="ok">
<fieldset class="fieldset_img">
<legend>图片展示</legend>
<ul id="ImgList">
<!--li>
<img id="img1" width="100" height="100" style="cursor:pointer;">
<br/>
<a href="#" name="img1" οnclick="DelImg(this)">删除</a>
</li-->
</ul>
</fieldset>
</div>
   
 </body>
</html>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值