Downloading files stored in SQL Server via SharePoint Web Part

In your web part render override, create a link that looks something like this:

<a href="http://your_intranet/path/to/page/with/webpart/Pages/default.aspx?getfileid=5">Get File with ID 5</a>

I'm hard coding the above because I'm assuming that you know how to query the database and display the relevant link on your web part.

Now, the code to download the file once the above link is clicked.

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<a href="http://your_intranet/path/to/page/with/webpart/Pages/default.aspx?getfileid=5">Get File with ID 5</a>");
            try
            {
                if (Page.Request.QueryString["getfileid"] != null)
                {
                    OpenSQLConnection();
                    cmd = new SqlCommand("SELECT FileName, Content, ContentType FROM TableName WHERE ID=" + Page.Request.QueryString["getfileid"], connection);
                    cmd.CommandType = CommandType.Text;
                    rdr = cmd.ExecuteReader();
                    if (rdr.Read())
                    {
                        try
                        {
                            byte[] fileData = (byte[])rdr["Content"];

                            Page.Response.Clear();
                            Page.Response.Buffer = true;
                            Page.Response.ContentType = rdr["ContentType"].ToString();
                            Page.Response.AddHeader("content-disposition", "attachment;filename=" + rdr["FileName"].ToString());
                            Page.Response.Charset = "";
                            Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                            Page.Response.BinaryWrite(fileData);
                            Page.Response.End();

                        }
                        catch (Exception ex)
                        {
                            // Error trying to download attachment.
                        }
                    }
                    else
                    {
                        // file not found.
                        writer.Write("File not found.");
                    }
                    rdr.Close();
                    CloseSQLConnection();
                }
            }
            catch (Exception ex)
            {
                CloseSQLConnection();
                // problem with connecting to db to get the file
            }
        }

On clicking that link, you will now be prompted to download the file and choose a location where you want to save that file (or just open it for viewing).

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.