Uploading files to SQL Server via SharePoint Web Part

Firstly, make sure that you have a varbinary and/or image field in your table since we are going to store the file you upload in binary form.

Again, let's start with the important variables:

        private HtmlInputFile inputFile = new HtmlInputFile();
        private Button btnSubmitFile = new Button();

 Then within the CreateChildControls Override:

        protected override void CreateChildControls()
        {
                inputFile.ID = "_fileUpload";
                this.Controls.Add(inputFile);

                btnSubmitFile.Text = "Submit Request";
                btnSubmitFile.Click += new EventHandler(btnSubmitFile_Click);
                this.Controls.Add(btnSubmitFile);
        }

Then within the Render Override:

        protected override void Render(HtmlTextWriter writer)
        {
                inputFile.RenderControl(writer);
                btnSubmitFile.RenderControl(writer);
        }

Then within the btnSubmitFile event which runs when the button is clicked

        void btnSubmitRequest_Click(object sender, EventArgs e)
        {
            // check for allowed extensions
            string AllowedExtensions = "'.doc','.xls','.bmp','.gif','.jpg','.pdf'";
            if (String.IsNullOrEmpty(inputFile.PostedFile.FileName))
            {
                // This means there is no file submitted
            }
            else
            {
                // check the extension of the file before uploading
                if (AllowedExtensions.Contains(System.IO.Path.GetExtension(inputFile.PostedFile.FileName)))
                {
                    // is one of the allowed extensions
                    try
                    {
                        UploadAttachments();
                    }
                    catch (Exception ex)
                    {
                        // problem uploading the file... handle the exception
                    }
                }
                else
                {
                    // file extension is not allowed
                }
            }
        }

        private void UploadAttachments()
        {
            // now check if there are any attachments.
            try
            {
                if (inputFile.PostedFile.FileName.Length != 0)
                {
                    // then there is a file to upload
                    HttpPostedFile objHttpPostedFile = inputFile.PostedFile;

                    // Find its length and convert it to byte array
                    int intContentlength = objHttpPostedFile.ContentLength;

                    // Create Byte Array
                    Byte[] bytFile = new Byte[intContentlength];

                    // Read Uploaded file in Byte Array
                    objHttpPostedFile.InputStream.Read(bytFile, 0, intContentlength);

                    OpenSQLConnection();
                    SqlCommand cmd = new SqlCommand("INSERT INTO TableName(FileName,ContentType,Content) VALUES(@FileName,@ContentType,@Content)", connection);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter("@FileName", inputFile.PostedFile.FileName));
                    cmd.Parameters.Add(new SqlParameter("@ContentType", inputFile.PostedFile.ContentType));
                    cmd.Parameters.Add(new SqlParameter("@Content", bytFile));

                    cmd.ExecuteNonQuery();
                    CloseSQLConnection();
                }
            }
            catch (Exception ex)
            {
                CloseSQLConnection();
                // Problem uploading the file into the database... handle the exception
            }
        }

        private void OpenSQLConnection()
        {
            connection = new SqlConnection("server=localhost;database=DatabaseName;Integrated Security=SSPI");
            connection.Open();
        }

        private void CloseSQLConnection()
        {
            connection.Close();
        }

Note that the code above checks only for the file extension, which can be easily changed by renaming the file. You could also check their content types (inputFile.PostedFile.ContentType) if you want to be sure that the file being uploaded is really what it claims to be.

Next blog will explain how to place a link in a web part to download the file that was just uploaded.

Leave a Comment

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