Avatar of Brian
Brian
Flag for United States of America asked on

FileUpload only PDF Files

Hello EE,

I have a scenario that is driving me crazy. I have the following code below that ONLY allows a user to upload .pdf files which is what I need. BUT, if the user does not select a file to upload then the code does not execute and instead the page postback to itself.

I tested my SP and they all seem fine, the problem has to do with my code not allowing updates unless I select a file to upload. If i only update the txtPhysicalDateCompleted Control then the page Postback to itself.

    protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
    {
        // Make sure a file has been successfully uploaded
        if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
        {
        }

        //Make sure we are dealing a .pdf file only
        string extension = Path.GetExtension(fuAnnualPhysicalForm.PostedFile.FileName).ToLower();
        string MIMEType = null;

        switch (extension)
        {
            case ".pdf":
                MIMEType = "application/pdf";
                break;
            default:
                //Invalid file type Error Message
                lblUploadTypeError.Text = "Only .pdf files are allowed";
            return;
        }

        //string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
        string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
        int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

        // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
        if ((fileSize < 1048576))
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            // Load PDF InputStream into Byte array
            byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
            fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
            cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
            cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
            cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
            cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
            cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

            if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
            {
                cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
            }
            else
            {
                cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
            }

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }

            catch (Exception ex)
            {
                lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
            }

            finally
            {
                Response.Redirect("AnnualPhysical_Success.aspx");
                conn.Close();
            }
        }

        else
        {
            lblFileSize.Text = "Your File has to be 5 MB or smaller";
        }
    }
ASP.NET.NET Programming

Avatar of undefined
Last Comment
Brian

8/22/2022 - Mon
kaufmed

Are you using the ASP.NET FileUpload control, or are you using a 3rd party upload control?
Brian

ASKER
ASP.NET FileUpload Control.
kaufmed

Wrap your code in an "if" check:
protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
{
    if (fuAnnualPhysicalForm.HasFile)
    {
        // your other code here
    }
}

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Brian

ASKER
Ok, I wrapped my code as you requested and I have no problem Insert the data but I'm unable to update the data. When I update nothing happens, no errors either.


protected void Page_Load(object sender, EventArgs e)
    {
        hf_AppID.Value = Session["pi_id"].ToString();

        if (!IsPostBack)
        {
            int pi_id = Convert.ToInt32(Session["pi_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_RetrieveAnnualPhysicalValuesByPI_ID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

            DataTable dtModify = new DataTable("Modify");

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtModify);

                if ((dtModify != null))
                {
                    DataRow data = dtModify.Rows[0];
                    hf_ap_id.Value = data["ap_id"].ToString();
                    txtPhysicalDateCompleted.Text = Convert.ToDateTime(data["ap_date"]).ToShortDateString();
                    lblFileNameUploaded.Text = "Your File has been uploaded: " + data["ap_pdf_filename"].ToString();

                    if (data["ap_section_complete"].ToString() == "1")
                    {
                        btn_SaveAnnualPhysical.Enabled = false;
                        cb_AnnualPhysical.Checked = true;
                    }

                    else
                    {
                        cb_AnnualPhysical.Checked = false;
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }

    protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
    {
        if (fuAnnualPhysicalForm.HasFile)
        {
            // Make sure a file has been successfully uploaded
            if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
            {
            }

            //Make sure we are dealing a .pdf file only
            string extension = Path.GetExtension(fuAnnualPhysicalForm.PostedFile.FileName).ToLower();
            string MIMEType = null;

            switch (extension)
            {
                case ".pdf":
                    MIMEType = "application/pdf";
                    break;
                default:
                    //Invalid file type Error Message
                    lblUploadTypeError.Text = "Only .pdf files are allowed";
                    return;
            }

            //string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
            string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
            int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if ((fileSize < 1048576))
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                // Load PDF InputStream into Byte array
                byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
                fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
                cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
                }

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
                }

                finally
                {
                    Response.Redirect("AnnualPhysical_Success.aspx");
                    conn.Close();
                }
            }

            else
            {
                lblFileSize.Text = "Your File has to be 5 MB or smaller";
            }
        }
    }
kaufmed

Which one is the update code?
Brian

ASKER
btn_SaveAnnualPhysical_Click is used to Insert and or Update. The SP used for this Event is listed below.


STORED PROCEDURE:

ALTER PROCEDURE [dbo].[WellnessChoice_InsertAnnualPhysical]

(
@pi_id int,
@ap_date datetime,
@ap_pdf_file image,
@ap_pdf_filename varchar(50),
@ap_pdf_mime varchar(50),
@ap_pdf_size varchar(50),
@ap_section_complete int
)

AS

UPDATE WellnessChoice_AnnualPhysical
      SET ap_date = @ap_date,
            ap_pdf_file = case when DATALENGTH(@ap_pdf_file) <= 4 then ap_pdf_file else @ap_pdf_file end,
            ap_pdf_filename = isnull(nullif(@ap_pdf_filename,''), ap_pdf_filename),
            ap_pdf_mime = isnull(nullif(@ap_pdf_mime,'application/octet-stream'), ap_pdf_mime),
            ap_pdf_size = isnull(nullif(@ap_pdf_size,0), ap_pdf_size),
            ap_section_complete = @ap_section_complete
      WHERE pi_id = @pi_id

IF @@ROWCOUNT = 0
      INSERT WellnessChoice_AnnualPhysical (pi_id, ap_date, ap_pdf_file, ap_pdf_filename, ap_pdf_mime, ap_pdf_size, ap_section_complete)
      VALUES (@pi_id, @ap_date, @ap_pdf_file, @ap_pdf_filename, @ap_pdf_mime, @ap_pdf_size, @ap_section_complete)
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
codingbeaver

You cannot update the database is because if a user does not select a file, then fuAnnualPhysicalForm.HasFile = false, then the whole block will be skipped. So according to your current logic, the update only happens when user selects a new file.

For us to better help, try explaining your business logic a bit more.
Brian

ASKER
Step 1: need the ability to upload a file.
Step 2: need ability to NOT overwrite and existing file if one is already present in the DB when just performing an update on another field.
Step 3: need ability to update file and it's info if user decides to reupload another file.

Please note: That if I use the following code below all my steps above work fine. The only problem that I have is when trying to ONLY specify that a user has to upload PDF files only.

THIS CODE WORKS AS NEEDED BELOW, I JUST NEED TO MAKE IT SO THAT THEY ONLY CAN UPLOAD PDF FILES:

protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
    {
        // Make sure a file has been successfully uploaded
        if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
        {
        }

        string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
        string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
        int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

        // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
        if ((fileSize < 1048576))
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            // Load PDF InputStream into Byte array
            byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
            fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
            cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
            cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
            cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
            cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
            cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

            if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
            {
                cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
            }
            else
            {
                cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
            }

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }

            catch (Exception ex)
            {
                lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
            }

            finally
            {
                Response.Redirect("AnnualPhysical_Success.aspx");
                conn.Close();
            }
        }

        else
        {
            lblFileSize.Text = "Your File has to be 5 MB or smaller";
        }
    }
codingbeaver

In your original post, you mentioned your problem is " if the user does not select a file to upload then the code does not execute and instead the page postback to itself. " However, in your post above, you said "Please note: That if I use the following code below all my steps above work fine. The only problem that I have is when trying to ONLY specify that a user has to upload PDF files only."

Those are two different problems.

Did you think that file extension check in your OP introduced the first problem? Based on the code you provided, you have the same problem when user does not select a file, no matter you have file extension check or not. If user does not select a file, and if you don't check fuAnnualPhysicalForm.HasFile, then fuAnnualPhysicalForm.PostedFile.FileName will give you a null reference error. Did you get any exception error with your original code when user does not select a file?

I suggest you to have a block for handling fuAnnualPhysicalForm.HasFile = true, then have a else block to handle fuAnnualPhysicalForm.HasFile = false.

 
protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
{
    if (fuAnnualPhysicalForm.HasFile)
    {
        // your other code here
    }
    else
    {
        // update other information
    }
}

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Brian

ASKER
Hi codingbeaver,

I apologize, I'm thinking about something different. You are correct.

Now I remember, sorry, have been at this for awhile :(

I need to make sure that the user is ONLY uploading a PDF file and if so execute the btn_SaveAnnualPhysical Code. If file is NOT pdf then display message to label control.

If a user decideds to ONLY insert/update a another field other than the FileUpload Control then allow to go through. If a user would like to overwrite the File with another PDF file then allow.

Where do I place the code I have now and a what section to your above post?
codingbeaver

Here is the basic logic you can refer to:
 
protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
{
    if (fuAnnualPhysicalForm.HasFile)
    {
        // user has uploaded a file
        // check file extension here
        // if file extension is ok
            // then proceed to update/insert record
        // if file extension is not OK
            // display error message and stop
    }
    else
    {
        // user does not select a new file to upload
        // then insert/update other fields other than 
        // the FileUpload control field
    }
}

Open in new window


If you have trouble understanding the above logic, let me know.
Brian

ASKER
Hi codingbeaver,

Ok, sorry for the delay. I believe I understood what you meant. So I made the following changes below and everything seems fine. Would you mind looking over the code below and giving me your thoughts?

Thanks again for your help and support!!!!



protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
    {
        if (fuAnnualPhysicalForm.HasFile)
        {
            // Make sure a file has been successfully uploaded
            if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
            {
            }

            //Make sure we are dealing a .pdf file only
            string extension = Path.GetExtension(fuAnnualPhysicalForm.PostedFile.FileName).ToLower();
            string MIMEType = null;

            switch (extension)
            {
                case ".pdf":
                    MIMEType = "application/pdf";
                    break;
                default:
                    //Invalid file type Error Message
                    lblUploadTypeError.Text = "Only .pdf files are allowed";
                    return;
            }

            // string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
            string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
            int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if ((fileSize < 1048576))
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                // Load PDF InputStream into Byte array
                byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
                fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
                cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
                }

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
                }

                finally
                {
                    Response.Redirect("AnnualPhysical_Success.aspx");
                    conn.Close();
                }
            }

            else
            {
                lblFileSize.Text = "Your File has to be 5 MB or smaller";
            }
        }

        else
        {
            // Make sure a file has been successfully uploaded
            if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
            {
            }

            string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
            string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
            int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if ((fileSize < 1048576))
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                // Load PDF InputStream into Byte array
                byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
                fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
                cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                }

                else
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
                }

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
                }

                finally
                {
                    Response.Redirect("AnnualPhysical_Success.aspx");
                    conn.Close();
                }
            }

            else
            {
                lblFileSize.Text = "Your File has to be 5 MB or smaller";
            }
        }
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
codingbeaver

1. If fuAnnualPhysicalForm.HasFile = true then this block is always false and wil not be executed at all:
if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
 {
 }
so you don't need this block.

2.  If fuAnnualPhysicalForm.HasFile = false, the above block is always true, but you have nothing in the block, so you don't need it either.

3. In your else block, because fuAnnualPhysicalForm.HasFile = false, no file has been uploaded, you should not try to get the file information from fuAnnualPhysicalForm.PostedFile. Also, since no file is uploaded, why do you still try to update the file information in your database?
Brian

ASKER
Ok, I believe I did Step 1 correctly but not sure what to change for Step 2.

>> Also, since no file is uploaded, why do you still try to update the file information in your database?
I believe the reason I did that is because my Save btn handles both Insert/Updates SP. So wouldn't I still need that for Step 2 in case a user wants to upload another file? If not needed can you modify the following code below to what I should have if need be?

    protected void btn_SaveAnnualPhysical_Click(object sender, EventArgs e)
    {
        if (fuAnnualPhysicalForm.HasFile)
        {
            //// Make sure a file has been successfully uploaded
            //if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
            //{
            //}

            //Make sure we are dealing a .pdf file only
            string extension = Path.GetExtension(fuAnnualPhysicalForm.PostedFile.FileName).ToLower();
            string MIMEType = null;

            switch (extension)
            {
                case ".pdf":
                    MIMEType = "application/pdf";
                    break;
                default:
                    //Invalid file type Error Message
                    lblUploadTypeError.Text = "Only .pdf files are allowed";
                    return;
            }

            // string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
            string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
            int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if ((fileSize < 1048576))
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                // Load PDF InputStream into Byte array
                byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
                fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
                cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
                }

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
                }

                finally
                {
                    Response.Redirect("AnnualPhysical_Success.aspx");
                    conn.Close();
                }
            }

            else
            {
                lblFileSize.Text = "Your File has to be 5 MB or smaller";
            }
        }

        else
        {
            // Make sure a file has been successfully uploaded
            if (fuAnnualPhysicalForm.PostedFile == null || string.IsNullOrEmpty(fuAnnualPhysicalForm.PostedFile.FileName) || fuAnnualPhysicalForm.PostedFile.InputStream == null)
            {
            }

            string MIMEType = fuAnnualPhysicalForm.PostedFile.ContentType;
            string filename = fuAnnualPhysicalForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
            int fileSize = fuAnnualPhysicalForm.PostedFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if ((fileSize < 1048576))
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "WellnessChoice_InsertAnnualPhysical";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                // Load PDF InputStream into Byte array
                byte[] imageBytes = new byte[fuAnnualPhysicalForm.PostedFile.InputStream.Length + 1];
                fuAnnualPhysicalForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
                cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                if (string.IsNullOrEmpty(txtPhysicalDateCompleted.Text))
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                }

                else
                {
                    cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtPhysicalDateCompleted.Text;
                }

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
                }

                finally
                {
                    Response.Redirect("AnnualPhysical_Success.aspx");
                    conn.Close();
                }
            }

            else
            {
                lblFileSize.Text = "Your File has to be 5 MB or smaller";
            }
        }
codingbeaver

>>>I believe the reason I did that is because my Save btn handles both Insert/Updates SP. So wouldn't I still need that for Step 2 in case a user wants to upload another file?

If user wants to upload another file and does select a file, then fuAnnualPhysicalForm.HasFile = true, so your code will execute the "if" block, instead of the "else" block. Does it make sense?
(fuAnnualPhysicalForm.HasFile is used to check if a file has been uploaded).

>>>If not needed can you modify the following code below to what I should have if need be?
If user chooses not to upload a file and clicks Save button, what information do you allow to update in database?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Brian

ASKER
>> If user chooses not to upload a file and clicks Save button, what information do you allow to update in database?

I apologize if I'm not making sense or confusing. Let me try to explain a little better.

Option 1: User uploads PDF FIle only

Option 2: User may NOT upload PDF file and he /she may only Insert / Update Date in txtPhysicalDateCompleted control.

Option 3: User may need to overwrite previous file that they uploaded if they made a mistake and uploaded wrong file, if so overwrite file in DB with new file.

Option 4:
ASKER CERTIFIED SOLUTION
codingbeaver

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Brian

ASKER
Ok, I copied your code but when the page first loads I get the following message below.

Error is on line 196.


Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1011: Empty character literal

Source Error:

Line 194:                  
Line 195:                  //cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
Line 196:                  cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = '';
Line 197:                  
Line 198:                  //cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
 
codingbeaver

Sorry, replace single quote to double quote.
 
//cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = "";

//cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = "application/octet-stream";

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Brian

ASKER
Hi codingbeaver:,

I found the problem. Please see below. And if that's all and nothing else needs changed let me know so that I can close the post. Thank you for your time, patience, and willing to help others!!!!!

DID NOT WORK: (SINGLE QUOTES)
cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = '';

cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = "application/octet-stream";

WORKED AS NEEDED WITH NO ISSUES FOR INSERT/UPDATE:
cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = "";

cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = "application/octet-stream";
Brian

ASKER
Hi codingbeaver,

Yes, that worked...

Thank you for your time, patience, and willing to help others!!!!!
codingbeaver

I am glad it works now.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Brian

ASKER
Thank you again for your time, patience and willing to help with this post. I truly apprecieate it!!!