Uploading & Downloading files in asp.net using C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • raja471
    New Member
    • Mar 2010
    • 7

    Uploading & Downloading files in asp.net using C#

    Haiii Everbody,

    I'm new to this forum, infact this is the first forum i hav ever joined.
    I need some help urgently as i'm reaching the deadline of my project.

    I created an asp.net website, where administrator will upload files to SQL database which is connected to the webpage. From the web page there will be a download link to download those uploaded files. I have been successful in uploading files to the database. But nothing is striking in my mind regarding how to download files directly from database using asp.net C#.

    Please help me in this regard.

    Thanks in advacne
  • raja471
    New Member
    • Mar 2010
    • 7

    #2
    Anyone....pleas e reply to my post....its very urgent

    Comment

    • CroCrew
      Recognized Expert Contributor
      • Jan 2008
      • 564

      #3
      Hello raja471,

      Glad to help out. But, first we are going to need more information.

      Are you storing the files in a BLOB field? Please post the code that you have so far so that we can provide you with the best fit solution to your question/problem.


      Happy Coding,
      CroCrew~

      Comment

      • raja471
        New Member
        • Mar 2010
        • 7

        #4
        Thank you for the reply.
        The following are the my aspx.cs files for uploading and donwloading files from the database.

        I have created a table in sql database which has columns like
        Code:
        ProductID -- int
        Name --- varchar(50)
        Type --- varchar(50)
        Description --- varchar(max)
        Doc --- varbinar(max)
        UploadFiles.asp x.cs
        Code:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Data.SqlClient;
        using System.Configuration;
        
        public partial class Upload : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
        
            }
            protected void uploading_Click(object sender, EventArgs e)
            {
                if (FileToUpload.PostedFile == null || String.IsNullOrEmpty(FileToUpload.PostedFile.FileName) || FileToUpload.PostedFile.InputStream == null)
                {
                    lit_Status.Text = "<br />Error - unable to upload file. Please try again.<br />";
                }
        
                else
                {
                    using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResourcesConnectionString1"].ConnectionString))
                    {
                        try
                        {
                            const string SQL = "INSERT INTO Resources (Name, Description, Price, FileType, Doc) VALUES (@FileName, @Description, @Price, @Type, @Doc)";
                            SqlCommand cmd = new SqlCommand(SQL, Conn);
                            cmd.Parameters.AddWithValue("@FileName", TextBox1.Text.Trim());
                            cmd.Parameters.AddWithValue("@Description", TextBox3.Text.Trim());
                            cmd.Parameters.AddWithValue("@Price", TextBox2.Text.Trim());
                            cmd.Parameters.AddWithValue("@Type", FileToUpload.PostedFile.ContentType);
        
                            byte[] imageBytes = new byte[FileToUpload.PostedFile.InputStream.Length + 1];
                            FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
                            cmd.Parameters.AddWithValue("@Doc", imageBytes);
        
                            Conn.Open();
                            cmd.ExecuteNonQuery();
                            lit_Status.Text = "<br />File successfully uploaded - thank you.<br />";
                            Conn.Close();
                        }
                        catch
                        {
                            Conn.Close();
                        }
                    }
                }
            }
        }

        DownloadFiles.a spx.cs

        Code:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Data.SqlClient;
        using System.Web.UI.WebControls;
        using System.Configuration;
        
        public partial class delFiles : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
        
            }
            protected void newFile_Click(object sender, EventArgs e)
            {
                Response.Redirect("Upload.aspx");
            }
            protected void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
            {
                if (e.CommandName == "Donwload")
                {
                    String[] Fileinfo = e.CommandArgument.ToString().Split(new char[] { ',' });
        
                    int ProductID = Int32.Parse(Fileinfo[0]);
                    String Name = Fileinfo[1];
        
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ResourcesConnectionString1"].ConnectionString))
                    {
                        SqlCommand com = new SqlCommand("select Doc from Resources Where ProductID=@ProductID");
        
                        com.Parameters.AddWithValue("@ProductID", ProductID);
                        com.Connection = con;
                        con.Open();
        
                        byte[] Doc = (Byte[])com.ExecuteScalar();
        
                        Response.AddHeader("Conetent-Disposition", "attachment;filename=" + Name + ".zip");
                        Response.ContentType = "application/octet-stream";
                        Response.BinaryWrite(Doc);
                    }
                }
        
        
            }
        }
        My code is working properly incase of uploading files. it is not responding when i click the download button.

        Please help me.....Thanks in advance.
        Last edited by Frinavale; Mar 29 '10, 01:45 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

        Comment

        • raja471
          New Member
          • Mar 2010
          • 7

          #5
          Hey .... I finally got the result....anywa y thanks for ur reply....i have one more problem.

          I need to create a paypal link to my website....when user clicks the download button, now the file is getting downloaded. Instead of that it download button should direct the page to paypal by taking the "name' and "price" fileds from the gridview. After the amount has been paid by the user in paypal it should redirect to "Save As" window for the corresponding file.

          It seems im asking for entire application, but like i said, im a beginner in asp.net. i just started a few days back. I cant provide any code also, because i have not done anuthing in this regard. But help is needed urgently.

          Please help me....

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            What have you tried so far to solve this problem?

            You could either have a link on the page that redirects the user to the PayPal page.

            Or you could have the server do the Redirect once the user clicks the link (or button).

            Or you could place another form on the page that submits to PayPal...


            -Frinny

            Comment

            • raja471
              New Member
              • Mar 2010
              • 7

              #7
              Thank you for the reply.

              Like i said before, i have a an upload page where i could upload files with filename and price to a SQL database. I have a datalist for these files in another page. No i want to put a buynow button in each item of the datalist which should take filename and price from the datalist iteself. is this possible for a buynow button to take the fileds from the datalist....if so how....i would be so greatful if u could explain me with an example.

              Thank you.

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                I would use a GridView control or a Repeater for this.

                Both of these controls bind to a data source and display it to the user in the way that you specified. With the GridView control you can add a button column to a grid that displays your items. With the Repeater control it's a little more flexible ...but you bind a button (or link) to the data in a similar way.

                Check out the these tools and choose according to what you think would be best for your application.

                -Frinny

                Comment

                • raja471
                  New Member
                  • Mar 2010
                  • 7

                  #9
                  Hai....Thank you for the reply.....It helped me a lot

                  Now i want to resolve another issue.

                  I have a table in databae which constists of a varbinary filed and some other fileds. I am dispaying this table in gridview in one page. I added a column in the same table with a button filed for each row. Now if i click that button the varbinary filed in that row of the table should get copied to anothe table which is already there in the database.

                  Suppose if i click the button in the first row, the varbinary filed in that table should get copied to new table and if a click button in second row....the already added varbinary should get replaced by the varbinary of second row, meaning everytime the data in the new table should get replaced by the button click....

                  Is there any way to do this....

                  A detailed explanation would be appreciated.

                  Thank you

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    I'm not exactly sure what you're trying to accomplish but it sounds like you already know what you need to do.

                    When the user clicks the button, get the ID of the row that the user clicked...make a call to the database and retrieve your binary for that row and then make another call to your database which updates the table with the binary data selected/retrieved.

                    -Frinny

                    Comment

                    • raja471
                      New Member
                      • Mar 2010
                      • 7

                      #11
                      haii....

                      Thank you for the reply...i solved that problem....now i need help in another issue.

                      I have a page having some paypal buynow buttons in gridview. When i click a particular buynow button in a particular row...after payment process it should redirect to detailsView of that record. i have created another page having detailsView of the same gridView table. So in returnUrl of paypal buynow button how can i give an url name like "http://www.raja.com/download?Produc tID=1". the product id will keep vary according to whch buynow button is clicked.

                      Thanks in advance.

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #12
                        Raja471,

                        What is your question?
                        I don't see a question at all in your last post. You just listed off a bunch of things that you have to do.

                        -Frinny

                        Comment

                        Working...