2016-08-21 81 views
0

我想验证多个上传的文件。它应该只接受.png.jpg文件。以下是我的代码:验证使用asp.net进行多文件上传C#web表单

protected void uploadFile_Click(object sender, EventArgs e) 
{ 
    if (multipleFile.HasFiles) 
    { 
     string filenameWithPath = string.Empty; 
     foreach (HttpPostedFile uploadedFile in multipleFile.PostedFiles) 
     { 
      filenameWithPath = System.IO.Path.Combine(
       Server.MapPath("~/Uploads/"), 
       uploadedFile.FileName); 
      uploadedFile.SaveAs(filenameWithPath); 
      ltStatusText.Text += "File-<b>" 
       + uploadedFile.FileName 
       + "</b> uploaded successfully.<br>"; 
     } 
    } 
} 
+0

见http://stackoverflow.com/a/38790454/5836671 – VDWWD

+0

HI zahed - 您能不能告诉我们什么你到目前为止已经尝试过,描述什么已经工作,哪些还没有工作? –

+0

我有多个文件上传,我想限制只上传JPG或PNG文件,而不是其他的扩展,谷歌搜索我没有找到任何示例。 @VinceBowdren – zahed

回答

0

我得到了答案。

下面是设计代码:

<body> 
<form id="form1" runat="server"> 
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" /> 
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadMultipleFiles" /> 
    <hr /> 
    <asp:Label ID="Information" runat="server" ForeColor="Green" /> 
</form> 
</body> 

下面是C#代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.IO; 
using System.Text.RegularExpressions; 

public partial class CS : System.Web.UI.Page 
{ 
protected void UploadMultipleFiles(object sender, EventArgs e) 
{ 
    foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles) 
    { 
    string fileName = Path.GetFileName(postedFile.FileName); 

     Regex reg = new Regex(@"^.*\.(jpg|JPG|jpeg|PNG|png)$"); 
     if (reg.IsMatch(fileName)) 
     { 
      postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName); 
      Information.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count); 
     } 
     else 
     { 
      Information.Text = "files have been uploaded fail , please check file format!"; 
     } 
    } 
    } 
    }