我们有时候作上传功能的时候会让用户上传多个图片或文件,一个一个上传吧有点麻烦。如果做成死的,一次上次,三个,或是五个的,有时候还不够用,这就很烦了。下面这种方法,在上传的地方加一个按钮,如果用户想上传几个就点几次,这样就会出现多个上传框,让他选择,好了,不多说了。下面是代码
前台代码
这里有一点要注意的是
<
input
type
=
"button"
value
=
'增加一个文件'
onclick
=
"addFile(<%=MaxFileCounts%>)"
/>这里面的
MaxFileCounts。这个是用户上传最大数的一个限制。你可以在这里写成死值,也可以在CS进行配置,主要看你的需求。
下面是cs文件了
好了,试一下吧,感谢还是很不错的
前台代码
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
- <script language="javascript" type="text/javascript">
- function addFile(max)
- {
- var file = document.getElementsByName("File");
- alert(file.length);
- if(file.length==1 && file[0].disabled==true)
- {
- file[0].disabled = false;
- return;
- }
- if(file.length<max)
- {
- var fileButton = '<br /><input type="file" size="50" name="File" />';
- alert(fileButton);
- document.getElementById("FileList").insertAdjacentHTML("beforeEnd",fileButton);
- }
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server" enctype="multipart/form-data">
- <p id="FileList">
- <input type="file" disabled="disabled" size="50" name="File" />
- </p>
- <input type="button" value='增加一个文件' onclick="addFile(<%=MaxFileCounts%>)" />
- <br />
- <br />
- <br />
- <asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
- </form>
- </body>
- </html>
下面是cs文件了
- 这里的MaxFileCount是在我配置文件写的,你可以根据你的情况写。
- public int MaxFileCounts = MaxFileCount;
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- HttpFileCollection fileList = HttpContext.Current.Request.Files;
- if (fileList == null)
- {
- return;
- }
- FileImage file = new FileImage();
- try
- {
- for (int i = 0; i < fileList.Count; i++)
- {
- HttpPostedFile postedFile = fileList[i];
- if (postedFile == null)
- continue;
- string fileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
- string extension = Path.GetExtension(postedFile.FileName);
- if (string.IsNullOrEmpty(extension) == true)
- continue;
- bool flag = false;
- foreach (string ext in AllowFileList)
- {
- if (ext == extension.ToLower())
- {
- flag = true;
- }
- }
- if (flag == false)
- continue;
- string storeUrl = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + extension.ToString();
- string Url = storeFilePath + storeUrl;
- string fullPath = Server.MapPath(Url);
- postedFile.SaveAs(fullPath);
- Hashtable ht = new Hashtable();
- ht.Add("Title",fileName);
- ht.Add("imgUrl",storeUrl);
- ht.Add("imgType",postedFile.ContentType);
- ht.Add("imgSize",postedFile.ContentLength);
- file.insertImage(ht);//这里是我的添加语句,你可写成你自己的。
- }
- }
- catch (Exception ex)
- {
- this.Label1.Text = ex.Message;
- }
- }
好了,试一下吧,感谢还是很不错的