locked
Best way to insert multiple images into database on 1 button_click RRS feed

  • Question

  • User-577741185 posted

    Hi everyone,

    I have 10 UploadFile controls, where the user can browse to an image to be inserted into the database on 1 button_click. What is the best way, code-wise, to insert the images into the database. I wouldn't want to call the method every time for each image. Is there a function or some kind of code I can use to insert all the images in the UploadFiles into the database on 1 button_click without calling the method 10 times?

    This is my code which inserts the image:

            int intImageSize = default(int);
            string strImageType = null;
            Stream ImageStream = default(Stream);
    
            // Gets the Size of the Image
            intImageSize = UploadFile.PostedFile.ContentLength;
    
            // Gets the Image Type
            strImageType = UploadFile.PostedFile.ContentType;
    
            // Reads the Image
            ImageStream = UploadFile.PostedFile.InputStream;
    
            byte[] ImageContent = new byte[intImageSize + 1];
            int intStatus = 0;
            intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    
            comm = new SqlCommand("INSERT INTO Images (image, image_type, eventID) VALUES (@image, @image_type, @eventID)", conn);
            comm.Parameters.AddWithValue("@image", ImageContent);
            comm.Parameters.AddWithValue("@image_type", strImageType);
            comm.Parameters.AddWithValue("@eventID", Convert.ToInt32(eventIDLabel.Text).ToString());
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();

    Thanks!

    Tuesday, September 29, 2009 7:58 AM

Answers

  • User-68639941 posted
    hi, 
    refer below code
     
    int intImageSize = default(int);
    		string strImageType = null;
    		Stream ImageStream = default(Stream);
    
    		FileUpload fileUpload=null;
    		for (int index = 0; index < 10; index++)
    		{
    			fileUpload=Page.Form.FindControl("UploadFile" + index.ToString()) as FileUpload;
    			// Gets the Size of the Image   
    			intImageSize = fileUpload.PostedFile.ContentLength;
    
    			// Gets the Image Type   
    			strImageType = fileUpload.PostedFile.ContentType;
    
    			// Reads the Image   
    			ImageStream = fileUpload.PostedFile.InputStream;
    
    			byte[] ImageContent = new byte[intImageSize + 1];
    			int intStatus = 0;
    			intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    
    			comm = new SqlCommand("INSERT INTO Images (image, image_type, eventID) VALUES (@image, @image_type, @eventID)", conn);
    			comm.Parameters.AddWithValue("@image", ImageContent);
    			comm.Parameters.AddWithValue("@image_type", strImageType);
    			comm.Parameters.AddWithValue("@eventID", Convert.ToInt32(eventIDLabel.Text).ToString());
    			conn.Open();
    			comm.ExecuteNonQuery();
    			conn.Close();
    		}
    


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 29, 2009 9:53 AM
  • User-68639941 posted

     hi,

     i have clearly asked you about the parent control you said fileupload controls are residing in Form but all are residing in "ContentPlacHolder"

    fileUpload = Page.Form.FindControl("FileUpload" + index.ToString()) as FileUpload;

    change the above code like below

     FileUpload fileUpload = this.Page.Form.FindControl("ContentPlaceHolder1").FindControl("FileUpload" + index.ToString())) as FileUpload;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 30, 2009 9:27 AM
  • User-68639941 posted

     hi,

     do you mean if the file has not be selected in the fileupload control?

    you can check if(fileUpload.PostedFile.FileName.Length!=0){ ... //code to insert}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 1, 2009 12:05 AM

All replies

  • User-68639941 posted

     hi,

     i think using for loop you can achieve this..

    Tuesday, September 29, 2009 9:18 AM
  • User-577741185 posted

    Thanks, I actually had that in mind, however I'm not sure how to apply it to my code.

    Tuesday, September 29, 2009 9:21 AM
  • User-68639941 posted
    hi, 
    refer below code
     
    int intImageSize = default(int);
    		string strImageType = null;
    		Stream ImageStream = default(Stream);
    
    		FileUpload fileUpload=null;
    		for (int index = 0; index < 10; index++)
    		{
    			fileUpload=Page.Form.FindControl("UploadFile" + index.ToString()) as FileUpload;
    			// Gets the Size of the Image   
    			intImageSize = fileUpload.PostedFile.ContentLength;
    
    			// Gets the Image Type   
    			strImageType = fileUpload.PostedFile.ContentType;
    
    			// Reads the Image   
    			ImageStream = fileUpload.PostedFile.InputStream;
    
    			byte[] ImageContent = new byte[intImageSize + 1];
    			int intStatus = 0;
    			intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    
    			comm = new SqlCommand("INSERT INTO Images (image, image_type, eventID) VALUES (@image, @image_type, @eventID)", conn);
    			comm.Parameters.AddWithValue("@image", ImageContent);
    			comm.Parameters.AddWithValue("@image_type", strImageType);
    			comm.Parameters.AddWithValue("@eventID", Convert.ToInt32(eventIDLabel.Text).ToString());
    			conn.Open();
    			comm.ExecuteNonQuery();
    			conn.Close();
    		}
    


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 29, 2009 9:53 AM
  • User-577741185 posted

    Thanks for that code, now there are 10 inserts being made, however, when I retrieve the images, only the image in the first uploadfile, which is called "UploadFile", is being displayed. The other ones show an empty image with an "x" on it.

    Tuesday, September 29, 2009 11:14 AM
  • User-577741185 posted

    Disregard the above post, I forgot to rename the fileupload. Now I'm getting

    Object reference not set to an instance of an object error on intImageSize = fileUpload.PostedFile.ContentLength;

    the fileUpload is null.

    Can anyone help me on this? Thanks!

    Tuesday, September 29, 2009 1:50 PM
  • User-68639941 posted

     hi,

     i think you are passing wrong FileUpload controls id , and also ensure the upload control directly residing inside the Form instead of any other controls such as panel etc...,

    you said u r having 10 fileupload control, tell me the names of all those controls. it suppose to have  fileuploadcontrolId1..fileuploadcontrolId2 etc..,

     

    Tuesday, September 29, 2009 11:59 PM
  • User-577741185 posted

    Hi, thanks for your help. My controls are called FileUpload1, FileUpload2, FileUpload3, FileUpload4, FileUpload5...till 10. They are on the page itself - not in any control.

    This is my code:

    int intImageSize = default(int);
            string strImageType = null;
            Stream ImageStream = default(Stream);
            FileUpload fileUpload = null;
            for (int index = 0; index < 10; index++)
            {
                fileUpload = Page.Form.FindControl("FileUpload" + index.ToString()) as FileUpload;
                // Gets the Size of the Image   
                intImageSize = fileUpload.PostedFile.ContentLength;
    
                // Gets the Image Type   
                strImageType = fileUpload.PostedFile.ContentType;
    
                // Reads the Image   
                ImageStream = fileUpload.PostedFile.InputStream;
    
                byte[] ImageContent = new byte[intImageSize + 1];
                int intStatus = 0;
                intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    
                comm = new SqlCommand("INSERT INTO Images (image, image_type, eventID) VALUES (@image, @image_type, @eventID)", conn);
                comm.Parameters.AddWithValue("@image", ImageContent);
                comm.Parameters.AddWithValue("@image_type", strImageType);
                comm.Parameters.AddWithValue("@eventID", Convert.ToInt32(eventIDLabel.Text).ToString());
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
            }

    Thanks, again!

    Wednesday, September 30, 2009 6:57 AM
  • User-68639941 posted

    hi,

     small mistake , change for loop index like below

    for (int index = 1; index <= 10; index++)   

            {   .......}

    Wednesday, September 30, 2009 7:04 AM
  • User-577741185 posted

    That didn't help. Frown

    Wednesday, September 30, 2009 7:20 AM
  • User-68639941 posted

      r u getting the below error on first iteration itself ?

    Object reference not set to an instance of an object error on intImageSize = fileUpload.PostedFile.ContentLength;

    the fileUpload is null.

    post your full code

    Wednesday, September 30, 2009 8:06 AM
  • User-577741185 posted

    Source:

    <%@ Page Title="" Language="C#" MasterPageFile="~/AdminMaster.master" AutoEventWireup="true"
        CodeFile="Events.aspx.cs" Inherits="Events" %>
    
    <%@ Register TagPrefix="ECalendar" Namespace="ExtendedControls" Assembly="EventCalendar" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
        <style type="text/css">
            .style1
            {
                width: 75%;
            }
            .style2
            {
                width: 861px;
            }
            .style3
            {
                width: 593px;
            }
            .style4
            {
                width: 442px;
            }
            .style5
            {
                width: 432px;
            }
            .style6
            {
                text-align: center;
            }
            .style10
            {
                width: 43%;
                height: 26px;
            }
            .style11
            {
                width: 7%;
                height: 26px;
            }
            .style16
            {
                text-align: center;
                font-weight: bold;
                font-size: large;
            }
            .style19
            {
                width: 7%;
            }
            .style20
            {
                width: 43%;
            }
            .style21
            {
                width: 72px;
            }
            .style22
            {
                width: 38%;
            }
        </style>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
        <h1>
            Events</h1>
        <ECalendar:EventCalendar ID="Calendar1" runat="server" BackColor="White" BorderColor="White"
            BorderWidth="1px" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="511px"
            Width="750px" FirstDayOfWeek="Monday" NextMonthText="Next >" PrevMonthText="< Prev"
            SelectionMode="DayWeekMonth" NextPrevFormat="FullMonth" ShowDescriptionAsToolTip="True"
            EventDateColumnName="" EventDescriptionColumnName="" EventHeaderColumnName=""
            ShowGridLines="True" OnDayRender="Calendar1_DayRender">
            <SelectedDayStyle BackColor="#333399" ForeColor="White" />
            <TodayDayStyle BackColor="#CCCCCC" />
            <SelectorStyle BorderColor="#404040" BorderStyle="Solid" />
            <DayStyle HorizontalAlign="Left" VerticalAlign="Top" Wrap="True" />
            <OtherMonthDayStyle ForeColor="#999999" />
            <NextPrevStyle Font-Size="8pt" ForeColor="#333333" Font-Bold="True" VerticalAlign="Bottom" />
            <DayHeaderStyle BorderWidth="1px" Font-Bold="True" Font-Size="8pt" />
            <TitleStyle BackColor="White" BorderColor="Black" BorderWidth="4px" Font-Bold="True"
                Font-Size="12pt" ForeColor="#333399" HorizontalAlign="Center" VerticalAlign="Middle" />
        </ECalendar:EventCalendar>
        <br />
        <b>
            <br />
        </b>
        <table class="style1" dir="ltr" frame="above" style="border-top-style: dotted; border-bottom-style: dotted;"
            title="Add New Event">
            <tr>
                <td class="style16" colspan="4">
                    Add New Event<br />
                </td>
            </tr>
            <tr>
                <td class="style21">
                    Title:
                </td>
                <td class="style22">
                    <asp:TextBox ID="titleTextBox" runat="server"></asp:TextBox>
                    <asp:Label ID="eventIDLabel" runat="server" Visible="False"></asp:Label>
                </td>
                <td class="style19">
                    Image1:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style21">
                    Date:
                </td>
                <td class="style22">
                    <asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox>
                </td>
                <td class="style19">
                    Image2:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style21">
                    Location:
                </td>
                <td class="style22">
                    <asp:TextBox ID="locationTextBox" runat="server"></asp:TextBox>
                </td>
                <td class="style19">
                    Image3:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style21">
                    Description:
                </td>
                <td class="style22">
                    <asp:TextBox ID="descriptionTextBox" runat="server"></asp:TextBox>
                </td>
                <td class="style19">
                    Image4:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style21">
                    Cost:
                </td>
                <td class="style22">
                    <asp:TextBox ID="costTextBox" runat="server"></asp:TextBox>
                </td>
                <td class="style19">
                    Image:5
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style6" colspan="2" rowspan="5">
                    <asp:Button ID="addEventButton" runat="server" OnClick="addEventButton_Click" Text="Add Event"
                        Height="26px" />
                </td>
                <td class="style19">
                    Image6:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style19">
                    Image7:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style19">
                    Image8:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
            <tr>
                <td class="style11">
                    Image9
                </td>
                <td class="style10">
                     
                </td>
            </tr>
            <tr>
                <td class="style19">
                    Image10:
                </td>
                <td class="style20">
                     
                </td>
            </tr>
        </table>
        <br />
        <br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:FileUpload ID="FileUpload2" runat="server" />
        <asp:FileUpload ID="FileUpload3" runat="server" />
        <asp:FileUpload ID="FileUpload4" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload5" runat="server" />
        <asp:FileUpload ID="FileUpload6" runat="server" />
        <asp:FileUpload ID="FileUpload7" runat="server" />
        <asp:FileUpload ID="FileUpload8" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload9" runat="server" />
        <asp:FileUpload ID="FileUpload10" runat="server" />
    </asp:Content>
    


    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.IO;
    using System.Web.UI.HtmlControls;
    
    
    public partial class Events : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        private DataTable GetEvents()
        {
            SqlConnection conn;
            string connectionString = ConfigurationManager.ConnectionStrings["RAJEConnectionString"].ConnectionString;
            conn = new SqlConnection(connectionString);
            SqlDataAdapter da = new SqlDataAdapter("SELECT date, description, title, eventID FROM Events", conn);
            da.Fill(dt);
    
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Calendar1.EventDateColumnName = "Date";
            Calendar1.EventDescriptionColumnName = "Description";
            Calendar1.EventHeaderColumnName = "Title";
    
            BindEvents();
        }
        private void BindEvents()
        {
            dt.Clear();
            Calendar1.EventSource = GetEvents();
        }
        protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
        {
            e.Day.IsSelectable = false;
            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToDateTime(row[0]).ToShortDateString() == e.Day.Date.ToShortDateString())
                {
                    Literal l = new Literal();
                    l.Visible = true;
                    l.Text = "<br/>" + row[1].ToString() + "<br/>";
                    e.Cell.Controls.Add(l);
    
                    HyperLink lnkEvent = new HyperLink();
                    lnkEvent.Text = "Details";
                    lnkEvent.Font.Size = FontUnit.Parse("8");
                    lnkEvent.Font.Bold = false;
                    lnkEvent.Font.Name = "Arial";
                    lnkEvent.NavigateUrl = "RegisterEvent.aspx?EventID=" + (row[3]);
                    lnkEvent.ForeColor = System.Drawing.Color.Navy;
                    lnkEvent.Font.Underline = false;
                    e.Cell.Controls.Add(lnkEvent);
                }
            }
        }
        protected void addEventButton_Click(object sender, EventArgs e)
        {
            SqlConnection conn;
            SqlCommand comm;
            SqlDataReader reader;
            string connectionString = ConfigurationManager.ConnectionStrings["RAJEConnectionString"].ConnectionString;
            conn = new SqlConnection(connectionString);
            comm = new SqlCommand("INSERT INTO Events (date, description, title, location, full_cost)" +
                " VALUES (@date, @description, @title, @location, @full_cost)", conn);
            conn.Open();
            comm.Parameters.AddWithValue("@date", dateTextBox.Text);
            comm.Parameters.AddWithValue("@description", descriptionTextBox.Text);
            comm.Parameters.AddWithValue("@title", titleTextBox.Text);
            comm.Parameters.AddWithValue("@location", locationTextBox.Text);
            comm.Parameters.AddWithValue("@full_cost", costTextBox.Text);
            comm.ExecuteNonQuery();
            conn.Close();
    
            comm = new SqlCommand("SELECT MAX(eventID) AS eventID FROM Events", conn);
            conn.Open();
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                string eventID = reader["eventID"].ToString();
                eventIDLabel.Text = eventID;
            }
            reader.Close();
            conn.Close();
    
            InsertImage();
            
            BindEvents();
            dateTextBox.Text = "";
            descriptionTextBox.Text = "";
            titleTextBox.Text = "";
            locationTextBox.Text = "";
            costTextBox.Text = "";
        }
        private void InsertImage()
        {
            SqlConnection conn;
            SqlCommand comm;
            string connectionString = ConfigurationManager.ConnectionStrings["RAJEConnectionString"].ConnectionString;
            conn = new SqlConnection(connectionString);
    
            int intImageSize = default(int);
            string strImageType = null;
            Stream ImageStream = default(Stream);
            FileUpload fileUpload = null;
            for (int index = 1; index <= 10; index++) 
            {
                fileUpload = Page.Form.FindControl("FileUpload" + index.ToString()) as FileUpload;
                // Gets the Size of the Image   
                intImageSize = fileUpload.PostedFile.ContentLength;
    
                // Gets the Image Type   
                strImageType = fileUpload.PostedFile.ContentType;
    
                // Reads the Image   
                ImageStream = fileUpload.PostedFile.InputStream;
    
                byte[] ImageContent = new byte[intImageSize + 1];
                int intStatus = 0;
                intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    
                comm = new SqlCommand("INSERT INTO Images (image, image_type, eventID) VALUES (@image, @image_type, @eventID)", conn);
                comm.Parameters.AddWithValue("@image", ImageContent);
                comm.Parameters.AddWithValue("@image_type", strImageType);
                comm.Parameters.AddWithValue("@eventID", Convert.ToInt32(eventIDLabel.Text).ToString());
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
            }
    
        }
    }
    

    The error is on intImageSize = fileUpload.PostedFile.ContentLength;

    Wednesday, September 30, 2009 8:14 AM
  • User-68639941 posted

     hi,

     i have clearly asked you about the parent control you said fileupload controls are residing in Form but all are residing in "ContentPlacHolder"

    fileUpload = Page.Form.FindControl("FileUpload" + index.ToString()) as FileUpload;

    change the above code like below

     FileUpload fileUpload = this.Page.Form.FindControl("ContentPlaceHolder1").FindControl("FileUpload" + index.ToString())) as FileUpload;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 30, 2009 9:27 AM
  • User-577741185 posted

    Hey, thanks alot for your help, it's working now! When you told me to ensure the fileuploads are on the page itself, contentplaceholder didn't come to mind. Sorry for tthe trouble.

    Wednesday, September 30, 2009 10:15 AM
  • User-577741185 posted

    1 more thing- if 1 of the the fileupload controls is null, i don't want it to be inserted. Would you know how to do that?

    Wednesday, September 30, 2009 11:07 AM
  • User-577741185 posted

    never mind, got it

    Wednesday, September 30, 2009 12:12 PM
  • User-68639941 posted

     hi,

     do you mean if the file has not be selected in the fileupload control?

    you can check if(fileUpload.PostedFile.FileName.Length!=0){ ... //code to insert}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 1, 2009 12:05 AM
  • User-577741185 posted

    Hi, yes, that's what I needed, but I already did

    if (fileUpload.FileName != "")

    Is there a benefit to what you did over this?

    Thursday, October 1, 2009 3:51 AM
  • User-68639941 posted

    hi,

    fileUpload.FileName - will gives only the filename whereas my code will give you the full path

    Thursday, October 1, 2009 3:58 AM
  • User-577741185 posted

    In that case, another 10 points for you! Thanks!

    Thursday, October 1, 2009 4:00 AM
  • User-577741185 posted

    wrong post

    Thursday, October 1, 2009 4:33 AM
  • User-940489780 posted

    Hi,

    i have use 5 upload controls and  i want to check whether any control HasFile or not, 

    so i f i talk about .CS file then how to insert those 5 image whether to write code for each scenario means

    scenario 1

    if(fileupload1.HasFile && fileupload2.HasFile &&fileupload3.HasFile && fileupload4.HasFile && fileupload5.HasFile )

    {

    then insert query

    }

     scenario 2

    if(fileupload1.HasFile && fileupload2.HasFile &&fileupload3.HasFile && fileupload4.HasFile )

    {

    then insert query

    }

    --

    --

    then there will be 25 scenario

    is there only solution to write 25 queries or there any other way out.................... plz help

    Thursday, June 23, 2011 8:27 AM