Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

How to upload and download files using asp.net and c# - Part 139

Suggested Videos
Part 136 - Provide capability to start and stop image slideshow
Part 137 - Add images to slideshow using xml file
Part 138 - Add images to slideshow using database table

In this video, we will discuss
1. Uploading files
2. Displaying the list of files that are already uploaded
3. Downloading files



The user interface to upload and download files, should be as shown below. 




When the files are uploaded, they should be uploaded to a folder on the web server. In our case, we will be uploading to "Data" folder.


WebForm1.aspx code:
<div style="font-family:Arial">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" 
    OnClick="Button1_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    OnRowCommand="GridView1_RowCommand" BackColor="White" 
    BorderColor="#CC9966" BorderStyle="None" 
    BorderWidth="1px" CellPadding="4">
    <Columns>
        <asp:TemplateField HeaderText="File" ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" 
                    CausesValidation="False" 
                    CommandArgument='<%# Eval("File") %>'
                    CommandName="Download" Text='<%# Eval("File") %>'>
                    </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Size" HeaderText="Size in Bytes" />
        <asp:BoundField DataField="Type" HeaderText="File Type" />
    </Columns>
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" 
        ForeColor="#FFFFCC" />
    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" 
        HorizontalAlign="Center" />
    <RowStyle BackColor="White" ForeColor="#330099" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" 
        ForeColor="#663399" />
    <SortedAscendingCellStyle BackColor="#FEFCEB" />
    <SortedAscendingHeaderStyle BackColor="#AF0101" />
    <SortedDescendingCellStyle BackColor="#F6F0C0" />
    <SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>
</div>

WebForm1.aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string fileName = FileUpload1.FileName;
        FileUpload1.PostedFile
            .SaveAs(Server.MapPath("~/Data/") + fileName);
    }

    DataTable dt = new DataTable();
    dt.Columns.Add("File");
    dt.Columns.Add("Size");
    dt.Columns.Add("Type");

    foreach (string strfile in Directory.GetFiles(Server.MapPath("~/Data")))
    {
        FileInfo fi = new FileInfo(strfile);
        dt.Rows.Add(fi.Name, fi.Length.ToString(), 
            GetFileTypeByExtension(fi.Extension));
    }

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

private string GetFileTypeByExtension(string fileExtension)
{
    switch (fileExtension.ToLower())
    {
        case ".docx":
        case ".doc":
            return "Microsoft Word Document";
        case ".xlsx":
        case ".xls":
            return "Microsoft Excel Document";
        case ".txt":
            return "Text Document";
        case ".jpg":
        case ".png":
            return "Image";
        default:
            return "Unknown";
    }
}

protected void GridView1_RowCommand(object sender, 
    GridViewCommandEventArgs e)
{
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "filename=" 
        + e.CommandArgument);
    Response.TransmitFile(Server.MapPath("~/Data/"
        + e.CommandArgument);
    Response.End();
}

Please make sure to include the following using declarations in the code behind file.
using System.IO;
using System.Data;

13 comments:

  1. YOUR VIDEOS ARE SIMPLY VERY CLEAR AND BRILLIANT

    ReplyDelete
  2. hello Sir,can you explain how to starting this tutorial?thats hard for me to follow this tutorial from the middle.thx alot.

    ReplyDelete
    Replies
    1. Follow this link: http://csharp-video-tutorials.blogspot.com/p/free-aspnet-video-tutorial.html

      And also subscribe & follow his youtube channel.

      Delete
  3. Hello Sir,
    Firstly, thanks for this video. However, it works fine on my local computer, but when I upload my website on Godaddy hosting, it does not work because of the code "Server.MapPath" I suppose. Could you tell how to fix it? Thanks.

    ReplyDelete
  4. i used d same code ..the images attached gets downloaded but it doesnot open saying "invalid file/format"

    ReplyDelete
  5. hello sir can u guide me to upload and download excel 2007 using asp.net . i have tried but i am strucked up with few issues of comaptability

    ReplyDelete
  6. Sir,
    Will you please discuss how to upload large files (e.g., 2 GB) with proper progress bar?
    Thanks

    ReplyDelete
  7. Hello Sir,

    I watched your videos and they are easy.

    Sir I wanted to know how can i upload videos into the database and show the uploaded videos in the gridview and when I click any video it should be played onto the same web page alongwith the gridview.

    Thanks

    ReplyDelete
  8. hello sir i want to download some video file in a table on server .
    i have the path of video file in database and i want to download in my local pc by using grid view table one by one ?

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hello sir I want to know how upload image on google drive in asp.net.

    ReplyDelete
  11. Hi sir nice video.....how to write into the textfile after publishing the pgm into the server....we are only able to write on the textfile locally to the desktop but failing write once we have published...we have given permission to the folder but receiving permission denied error when tried it from server.....Thank you in advance....


    string physicalPath = (@"D:\FlashdataLabel\text.txt");

    File.WriteAllText(physicalPath, String.Empty);
    FileStream stream = new FileStream(physicalPath, FileMode.Open, FileAccess.ReadWrite);
    StreamWriter writer = new StreamWriter(stream);
    SqlConnection con6 = new SqlConnection(constr6);
    con6.ConnectionString = constr6;
    SqlCommand com = new SqlCommand(" select PMax,VOC,ISC,VPM,IPM,PSV,AssignMSN,MSN_Mat,PSN from [LabelMSN]where PSN='" + txtpsn.Text + "' order by id desc", con6);
    con6.Open();
    SqlDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {

    writer.Write(reader["PMax"].ToString());
    writer.Write(",");
    writer.Write(reader["VOC"].ToString());
    writer.Write(",");
    writer.Write(reader["ISC"].ToString());
    writer.Write(",");
    writer.Write(reader["VPM"].ToString());
    writer.Write(",");
    writer.Write(reader["IPM"].ToString());
    writer.Write(",");
    writer.Write(reader["PSV"].ToString());
    writer.Write(",");
    writer.Write(reader["AssignMSN"].ToString());
    writer.Write(",");
    writer.Write(reader["MSN_Mat"].ToString());
    writer.Write(",");
    writer.Write(reader["PSN"].ToString());
    //writer.WriteLine();
    }
    reader.Close();
    writer.Close();
    stream.Close();
    con6.Close();


    }

    ReplyDelete
  12. Can you guide me How to open file directly in word excel of pdf application.

    ReplyDelete

It would be great if you can help share these free resources