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' 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" />
<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="上傳" onclick="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='刪除' 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-->
昨天為了回答百度知道上的問題,又用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"/> ';
html+='<input type="button" value="新增" onclick="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)+'" onclick="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="新增" onclick="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" onclick="DelImg(this)">刪除</a>
</li-->
</ul>
</fieldset>
</div>
</body>
</html>