2014-09-11 6 views
0

ASPX:расширение Validate файла для загрузки нескольких файлов на папку

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" /><br /> 
      <asp:Label ID="Label2" runat="server" Text="Invalid File. Please upload a File with Extension .JPEG , .JPG, .PNG" ForeColor="Red" Visible="false"></asp:Label><br /><br /> 
     <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" /> 
    <div style="width:50%; float:left; height:400px; overflow:auto;"> 
     <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"> 
     <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 
      <Columns> 
       <asp:TemplateField> 
        <ItemTemplate> 
         <asp:CheckBox ID="CheckBox1" runat="server" /> 
        </ItemTemplate> 
       </asp:TemplateField> 
       <asp:BoundField DataField="Text" HeaderText="Image Name" /> 
       <asp:ImageField DataImageUrlField="Value" HeaderText="Image" ControlStyle-Height="100" ControlStyle-Width="100" /> 
      </Columns> 
     <EditRowStyle BackColor="#999999" /> 
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
     <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
     <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
     <SortedAscendingCellStyle BackColor="#E9E7E2" /> 
     <SortedAscendingHeaderStyle BackColor="#506C8C" /> 
     <SortedDescendingCellStyle BackColor="#FFFDF8" /> 
     <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
     </asp:GridView> 
     </div> 

C#:

protected void Button1_Click(object sender, EventArgs e) 
    { 
     DateTime curr = DateTime.Now; 
     DateTime INDIAN_ZONE = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(curr, "India Standard Time"); 

     if (FileUpload1.HasFile) 
     { 
      HttpFileCollection hfc = Request.Files; 
      for (int i = 0; i < hfc.Count; i++) 
      { 
       HttpPostedFile hpf = hfc[i]; 
       if (hpf.ContentLength > 0) 
       { 
        string FileExtention = System.IO.Path.GetExtension(FileUpload1.FileName); 
        if (FileExtention == ".jpg") 
        { 
         string time1 = INDIAN_ZONE.ToString("MM-dd-yyyy_hhmmss"); 
         string directoryPath = Server.MapPath(string.Format("./upload/" + TextBox1.Text)); 
         if (!Directory.Exists(directoryPath)) 
         { 
          Directory.CreateDirectory(directoryPath); 
         } 
         else 
         { 
         } 

         string fileName = Path.GetFileName(hpf.FileName); 
         fileName = time1 + fileName; 
         string path = "./upload/" + TextBox1.Text + "/"; 
         hpf.SaveAs(Server.MapPath(path) + fileName); 
        } 
        else 
        { 

        } 
       } 
      } 

      string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/" + TextBox1.Text + "/")); 
      List<ListItem> files = new List<ListItem>(); 
      foreach (string filePath in filePaths) 
      { 
       string fileName1 = Path.GetFileName(filePath); 
       files.Add(new ListItem(fileName1, "~/upload/" + TextBox1.Text + "/" + fileName1)); 
      } 
      GridView1.DataSource = files; 
      GridView1.DataBind(); 
     } 
     else 
     { 
      string time1 = INDIAN_ZONE.ToString("MM-dd-yyyy_hhmmss"); 
      string directoryPath = Server.MapPath(string.Format("./upload/" + TextBox1.Text)); 
      if (!Directory.Exists(directoryPath)) 
      { 
       Directory.CreateDirectory(directoryPath); 
      } 
      else 
      { 
      } 
     } 
    } 

Я использую ASP.Net и C#. Когда я нажимаю кнопку «Загрузить», я хочу проверить каждый файл в FileUpload, если расширение файла является допустимым (JPEG, JPG, PNG), а затем сохранить файл в папке, если какой-либо файл не является допустимым, а затем показать это имя файла на ярлыке и ничего не делать. Как достичь этой проблемы.

ответ

0

Я думаю, что это не будет хорошим способом показать ошибку при каждой загрузке файла, поскольку файлы в цикле загружаются, поэтому на ярлыке будет отображаться только последний файл с любым другим расширением, который добавляет имена файлов в строка и в конце всех файлов были загружены, показывая метку, что следующие файлы не были загружены, или вы можете создавать метки во время выполнения всякий раз, когда загружается файл с другим расширением.

string filenames=""; 
if(extension="JPG") 
uploadfile() 
else 
filenames+=hpf.FileName+","; 

filenames.TrimEnd(","); 
label.Text="Following files have not been uploaded "+filenames; 

Method2

if(extension="JPG") 
uploadfile() 
else 
Label lb=new Label(); 
lbl.Text=hpf.FileName+" not uploaded please upload with JPG"; 
//Add lbl to your div or any other control. 
Смежные вопросы