For Asp.netProgram, We should provide a convenient user interface as much as possible, and reduce page return is one of them.
This article demonstrates how to upload multiple files at a time. You can control the number of uploaded files at Will on the client side, but note that the total file size cannot be too large; otherwise, an exception is thrown. The solution for uploading large files is beyond the scope of this article.
Here is a key point that you should not ignore, otherwise the program will not work properly.
The enctype = "multipart/form-Data" attribute of form must be specified.
CodeAs follows:
<% @ Page Language = "C #" codebehind = "multiattchments. aspx. cs" autoeventwireup = "false" inherits = "webapplication3.multiattchments" %>
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<SCRIPT>
Function addattachments ()
{
Document. getelementbyid ('Attach '). innertext = "add attachment ";
TB = Document. getelementbyid ('attachances ');
Newrow = Tb. insertrow ();
Newrow. insertcell (). innerhtml = "<input name = 'file' size = '50' type = 'file'> <input type = button value = 'delete' onclick = 'delfile (this. parentelement. parentelement. rowindex) '> ";
}
Function delfile (INDEX)
{
Document. getelementbyid ('attachances'). deleterow (INDEX );
TB. Rows. length> 0? Document. getelementbyid ('Attach '). innertext = "add attachment": Document. getelementbyid ('Attach'). innertext = "add attachment ";
}
</SCRIPT>
</Head>
<Body ms_positioning = "gridlayout">
<Form ID = "form1" method = "Post" runat = "server" enctype = "multipart/form-Data">
<Div> <Table id = "attachments"> </table> </div> <span> </span> <a id = "Attach "Style =" font-family:; font-size: 9pt; "Title =" if you want to send multiple attachments, you only need to click "add attachment" multiple times, note that the total number of attachments cannot exceed the size limit. "Onclick =" addattachments ();"
Href = "javascript:;" name = "Attach"> Add an attachment </a>
<Br>
<Asp: button id = "btnsend" runat = "server" text = "Upload"> </ASP: button>
</Form>
</Body>
</Html>
Private void btnsend_click (Object sender, system. eventargs E)
{
Stringbuilder sb = new stringbuilder ();
Int attcount = 0;
String filepath = "";
For (INT I = 0; I <request. Files. Count; I ++)
{
If (request. Files [I]. contentlength> 0)
{
Filepath = request. Files [I]. filename;
SB. append ("Files" + attcount ++ ":" + filepath + "<br> ");
Request. Files [0]. saveas (server. mappath ("./") + filepath. substring (filepath. lastindexof ("\") + 1 ));
}
}
SB. insert (0, "you upload" + attcount + "files. <br> ");
Response. Write (sb. tostring ());
}