日期:2014-05-18 浏览次数:20434 次
前台: <head runat="server"> <title>无标题页</title> <script language="JavaScript"> function addFile() { var str = '<BR><INPUT type="file" size="50" NAME="File" runat="server">' document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str) } </script> </head> <body> <form id="form1" runat="server"> <div> <table class="fullwidth" align="center"> <TR> <TD vAlign="top">Attachment :</TD> <TD> <P id="MyFile"><input id="filMyFile" type="file" size="50" name="filMyFile"> <input onclick="addFile()" type="button" value="Add"></P> <asp:label id="lblAttachmentError" runat="server" ForeColor="Red"></asp:label><BR> <asp:button id="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"></asp:button><asp:label id="lblAttachment" runat="server"></asp:label></TD> </TR> </table> </div> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /><br /> <asp:Label ID="Label1" runat="server" Width="119px"></asp:Label> </form> </body> 后台: protected void btnUpload_Click(object sender, EventArgs e) { HttpFileCollection files = HttpContext.Current.Request.Files; for (int i = 0; i < files.Count; i++) { if (i < files.Count && i < 10) { if (files[i].FileName != "" || files[i] != null) { int FileSize = 6 * 1024 * 1024; HttpPostedFile myFile = files[i]; string strFilePath = myFile.FileName.ToString().Trim(); this.lblAttachmentError.Text = "<" + strFilePath + ">"; // Show file name int nFindSlashPos = strFilePath.Trim().LastIndexOf("\\") + 1; string UploadFileName = strFilePath.Substring(nFindSlashPos); string FileName = string.Format("{0:yyMMdd}", DateTime.Now) + "-" + UploadFileName; if (myFile.FileName.Trim() == "") // Empty value in Browse Box { this.lblAttachmentError.Text = "No file selected."; return; } if (myFile.ContentLength != 0) { if (myFile.ContentLength > FileSize) { this.lblAttachmentError.Text = "File Size is limited to 6 MB only."; return; } this.lblAttachment.Text += "<BR>" + FileName; this.lblAttachmentError.Text = ""; myFile.SaveAs(@"D:\" + FileName);