File Upload with validation and Download,Delete in Asp.Net

Description:- 

Here we will Check when we Upload file using FileUpload Control in dot net and also we will check size of that file, type of file and if file selected or not when all condition successfully pass that whatever file we have selected for upload that file will upload in server. Here I have given download when you select file from Gridview then file download automatically and when you want delete file from server also you can delete as well.

Create table in Sql and Name it File_Mst.

CREATE TABLE [dbo].[File_Mst](
      [FileID] [bigint] IDENTITY(1,1) NOT NULL,
      [FileName] [varchar](50) NOT NULL,
      [FileType] [varchar](50) NOT NULL,
      [FileData] [varbinary](max) NOT NULL,
 CONSTRAINT [PK_File_Mst] PRIMARY KEY CLUSTERED
(
      [FileID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Html Markup:-

<div style="width: 400px; margin-left: 240px; margin-top: 90px;">
  <table>
    <tr>
      <td>
        <asp:FileUpload ID="FileUpload2" runat="server" />
      </td>
      <td>
        <asp:Button ID="btnFUClick" runat="server" Text="Button" OnClick="btnFUClick_Click" />
      </td>
    </tr>
    <tr>
      <td>
        <asp:Label ID="lblmessage" runat="server" />
      </td>
    </tr>
  </table>
</div>
<div style="width: 400px; margin-left: 240px; margin-top: 20px;">
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
    <Columns>
      <asp:TemplateField HeaderText="File ID">
        <ItemTemplate>
          <asp:Label ID="lblfileID" runat="server" Text='<%# Eval("FileID") %>'></asp:Label>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="File Name">
        <ItemTemplate>
          <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("FileName") %>' Height="30px" Width="50px" />
          <asp:LinkButton ID="lnkDownload1" Text='<%# Eval("FileName") %>' CommandArgument='<%# Eval("FileName") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="File Type">
        <ItemTemplate>
          <asp:Label ID="lblfiletype" runat="server" Text='<%# Eval("FileType") %>'></asp:Label>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Action">
        <ItemTemplate>
          <asp:LinkButton ID="lnkDelete" Text="Delete" CommandArgument='<%# Eval("FileID") %>' runat="server" OnClick="DeleteFile" />
        </ItemTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
</div>

Code behind:-

protected void btnFUClick_Click(object sender, EventArgs e)
{
  if (FileUpload2.HasFile)
  {
    try
    {
      if (FileUpload2.PostedFile.ContentType == "image/jpeg" || FileUpload2.PostedFile.ContentType == "image/png")
      {
        if (FileUpload2.PostedFile.ContentLength < 102400)
        {
          string FileName = FileUpload2.FileName;
          string filename = "~/MyFiles/" + Path.GetFileName(FileName);
          string FileExt = Path.GetExtension(FileName);
          string filetype = string.Empty;
          Stream str = FileUpload2.PostedFile.InputStream;
          BinaryReader br = new BinaryReader(str);
          Byte[] size = br.ReadBytes((int)str.Length);
          FileUpload2.SaveAs(Server.MapPath("~/MyFiles/") + FileName);
          lblmessage.ForeColor = Color.Green;
          lblmessage.Text = "Upload status: File uploaded!";
          con = new SqlConnection(CS);
          cmd = new SqlCommand();
          cmd.CommandText = "insert into File_Mst(FileName,FileType,FileData) values(@Name,@Type,@Data)";
          cmd.Connection = con;
          //cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.AddWithValue("@Name", filename);
          cmd.Parameters.AddWithValue("@Type", FileExt);
          cmd.Parameters.AddWithValue("@Data", size);
          con.Open();
          cmd.ExecuteNonQuery();
          BindGridviewData();
        }
        else
        {
          lblmessage.ForeColor = Color.Red;
          lblmessage.Text = "Upload status: The file has to be less than 100 kb!";
        }
      }
      else
      {
        lblmessage.ForeColor = Color.Red;
        lblmessage.Text = "Upload status: Only JPEG files are accepted!";
      }
    }
    catch (Exception ex)
    {
      lblmessage.ForeColor = Color.Red;
      lblmessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
    }
  }
}

private void BindGridviewData()
{
  using (con = new SqlConnection(CS))
  {
    using (SqlCommand cmd = new SqlCommand())
    {
      cmd.CommandText = "select * from File_Mst";
      cmd.Connection = con;
      con.Open();
      GridView1.DataSource = cmd.ExecuteReader();
      GridView1.DataBind();
      con.Close();
    }
  }
}

protected void DownloadFile(object sender, EventArgs e)
{
  string filePath = (sender as LinkButton).CommandArgument;
  Response.ContentType = ContentType;
  Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
  Response.WriteFile(filePath);
  Response.End();
}

protected void DeleteFile(object sender, EventArgs e)
{
  string filePath1 = (sender as LinkButton).CommandArgument;
  using (con = new SqlConnection(CS))
  {
    using (SqlCommand cmd = new SqlCommand())
    {
      cmd.CommandText = "delete from File_Mst where FileID=" + filePath1;
      cmd.Connection = con;
      con.Open();
      cmd.ExecuteNonQuery();
      con.Close();
    }
  }
  //Response.ContentType = ContentType;
  //File.Delete(filePath1);
  Response.Redirect(Request.Url.AbsoluteUri);
}

Now check in your Webpage in browser for Validation. Download and Delete.

Related Posts

Previous
Next Post »

Thanks for comments.....