asp.net 動態添加多附件上傳. 最近有人問起動態多檔案上傳,想要做到類似於郵箱添加附件的效果,這個功能其實比較簡單,就是往form中添加file元素。在使用者選擇完檔案後,再添加一個file控制項,由於file控制項過多,視覺上不好看,所以隱藏之前的控制項,保持頁面上只有一個控制項,同時把檔案名稱添加到附件列表中。
注意:頁面上初始的file控制項必須有runat="server"標誌。也就是說,這個頁面上必須至少有一個runat="server"的file控制項,否則後台接收不到Request.Files。 < FORM id ="form1" runat ="server" >
< DIV id ="div1" >
< INPUT ID ="File1" TYPE ="file" NAME ="File1" runat ="server" >
< INPUT TYPE ="button" VALUE ="添加附件" onclick ="javascript:AddFile();" >
< INPUT TYPE ="button" VALUE ="刪除附件" onclick ="javascript:RemoveFile();" >
< ASP:LISTBOX id ="ListBox1" Width ="200px" Height ="100px" runat ="server" ></ ASP:LISTBOX >
< ASP:BUTTON id ="Button1" runat ="server" Text ="儲存" Width ="60px" ></ ASP:BUTTON >
</ DIV >
< ASP:LITERAL ID ="lResult" Runat ="server" ></ ASP:LITERAL >
</ FORM >
< SCRIPT language = " javascript " >
<!--
function AddFile()
{
var file = document.getElementById( " div1 " ).firstChild;
if (file.value == "" )
{
alert( " 請選擇檔案! " );
return ;
}
var ary = file.value.split( " / " );
var filename = ary[ary.length - 1 ];
var bAddFile = true ;
if (CheckOptionsExists(filename,document.getElementById( " ListBox1 " )))
{
alert( " 檔案已經存在列表中! " );
div1.removeChild(file);
bAddFile = false ;
}
var f = document.createElement( " input " );
f.type = " file " ;
f.name = " file "
div1.insertBefore(f,div1.firstChild);
if ( ! bAddFile)
{
return
}
var o = new Option();
o.innerText = filename;
o.value = file.uniqueID;
document.getElementById( " ListBox1 " ).appendChild(o);
file.style.display = " none " ;
}
function RemoveFile()
{
var lst = document.getElementById( " ListBox1 " );
if (lst.selectedIndex == - 1 )
{
alert( " 請選擇要刪除的附件! " );
return ;
}
var id = lst.value;
div1.removeChild(document.all[id]);
lst.removeChild(lst.options[lst.selectedIndex]);
div1.firstChild.style.display = "" ;
}
// 檢查選項是否存在.
function CheckOptionsExists(value,ddl)
{
for ( var i = 0 ;i < ddl.options.length;i ++ )
{
if (ddl.options[i].innerText == value)
{
return true ;
}
}
return false ;
}
// -->
</ SCRIPT >
後台代碼就比較簡單了。沒有過多的處理,只是一個簡單的儲存。
private void Button1_Click( object sender, System.EventArgs e)
{
for ( int i = 0 ;i < Request.Files.Count;i ++ )
{
if (Request.Files[i].ContentLength > 0 )
{
string filename = System.IO.Path.GetFileName(Request.Files[i].FileName);
Request.Files[i].SaveAs(Server.MapPath(filename));
this .ListBox1.Items.Add( new ListItem(filename,filename));
}
this .lResult.Text = " 儲存成功! " ;
}
}