How can I select and display different images using a single fileupload control?

Donald Symmons 2,861 Reputation points
2024-01-01T23:55:14.7+00:00

I have a fileupload control and about 2 to 3 image controls. I want to be able to use this fileupload control to upload images and display them in their respective image controls.

For example, if I click on the fileupload, it will take me to my local storage where I select an image, then the image will be displayed in the first image control. I then click the same fileupload control and select another image, the second image will be displayed in the second image control, and so on....

Is that possible please?

I am guessing that a fileuplaod control is attached to one image at a time. Maybe using an input control could give the desired outcome.

<asp:FileUpload ID="FileUpload1" runat="server" />
                        <div class="certcontain col-sm-8" runat="server" id="section" style="width: 100%;">
                            <asp:Image Class="imgfile" ID="imgfile" runat="server" />
                            <asp:Image Class="imgfile" ID="Image1" runat="server" />
                            <asp:Image Class="imgfile" ID="Image2" runat="server" />
                        </div>
<script type="text/javascript">
        $(function () {
            var fileUpload = $("[id*=FileUpload1]");
            var img = $("[id*=imgfile]");
            var img = $("[id*=Image1]");
            var img = $("[id*=Image2]");
            img.click(function () { fileUpload.click(); });
            fileUpload.change(function () {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $("[id*=imgfile]").attr("src", e.target.result);
                    $("[id*=Image1]").attr("src", e.target.result);
                    $("[id*=Image2]").attr("src", e.target.result);
                }
                reader.readAsDataURL($(this)[0].files[0]);
            });
        });
    </script>
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,596 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,404 questions
0 comments No comments
{count} votes

Accepted answer
  1. SurferOnWww 2,406 Reputation points
    2024-01-02T02:02:01.99+00:00

    Is that possible please?

    Yes, you can do so only at the client side. Please try the following code. You can simply copy and paste to see it works.

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="WebForm32.aspx.cs" 
        Inherits="WebForms1.WebForm32" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script type="text/javascript">
            let fileUpload, img1, img2, img3;
            let count = 0;
    
            // async method to obtain Data url from File object given to argument
            const CreateDataUrl = file => {
                return new Promise(resolve => {
                    const reader = new FileReader();
                    reader.addEventListener('loadend',
                        e => resolve(e.target.result));
                    reader.readAsDataURL(file);
                });
            };
    
            window.addEventListener('DOMContentLoaded', () => {
    
                fileUpload = document.getElementById("<%=FileUpload1.ClientID%>");
                img1 = document.getElementById("<%=Image1.ClientID%>");
                img2 = document.getElementById("<%=Image2.ClientID%>");
                img3 = document.getElementById("<%=Image3.ClientID%>");
                const images = [img1, img2, img3];
    
                if (window.File && window.FileReader && window.FileList) {
    
                    // selection of file on FileUpload by user fires change event.
                    // attach listener to the event to call CreateDataUrl method and
                    // set the returned Data Url to img.src.
                    fileUpload.addEventListener('change', async () => {
                        if (count < images.length) {
                            images[count].src = await CreateDataUrl(fileUpload.files[0]);
                        }
                        count++;
                    });
                }
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Image ID="Image1" runat="server" />
            <asp:Image ID="Image2" runat="server" />
            <asp:Image ID="Image3" runat="server" />
        </form>
    </body>
    </html>
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Lan Huang-MSFT 28,826 Reputation points Microsoft Vendor
    2024-01-02T03:43:46.37+00:00

    Hi @Donald Symmons,

    I guess it is possible, my idea is that you can upload to database and then get the images from the database and then delete the unwanted ones. This method should be more convenient when you want to upload multiple images.

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
    <br />
    <asp:Label ID="lblMessage" runat="server" Text="" Font-Names="Arial"></asp:Label>
    <hr />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="Id" OnRowDeleting="GridView1_RowDeleting">
        <Columns>
           
            <asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# ToBase64(Eval("Data")) %>' />
                </ItemTemplate>
            </asp:TemplateField>
              <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
        </Columns>
    
    </asp:GridView>
    
     protected void Page_Load(object sender, EventArgs e)
     {
         if (!this.IsPostBack)
         {
           
             BindGridView();
         }
     }
    
     protected string ToBase64(object data)
     {
         byte[] bytes = (byte[])data;
         string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
         return "data:image/png;base64," + base64String;
     }
    
    
     protected void Upload(object sender, EventArgs e)
     {
         string filePath = string.Empty;
         string contenttype = string.Empty;
         string filename = string.Empty;
         byte[] bytes = null;
         if (this.FileUpload1.HasFile)
         {
             filePath = FileUpload1.PostedFile.FileName;
             filename = Path.GetFileName(filePath);
             string ext = Path.GetExtension(filename).ToLower();
             contenttype = string.Empty;
    
             switch (ext)
             {
                 case ".jpg":
                     contenttype = "image/jpg";
                     break;
                 case ".png":
                     contenttype = "image/png";
                     break;
                 case ".gif":
                     contenttype = "image/gif";
                     break;
             }
    
             using (Stream fs = FileUpload1.PostedFile.InputStream)
             {
                 using (BinaryReader br = new BinaryReader(fs))
                 {
                     bytes = br.ReadBytes((Int32)fs.Length);
                 }
             }
         }
         else
         {
             filename = "Default.png";
             contenttype = "image/png";
             System.Drawing.Image defaultImage = System.Drawing.Image.FromFile(Server.MapPath("~/Images/Default.png"));
             using (MemoryStream ms = new MemoryStream())
             {
                 defaultImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                 bytes = ms.ToArray();
             }
         }
    
         string query = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)";
         string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
         using (SqlConnection con = new SqlConnection(constr))
         {
             using (SqlCommand cmd = new SqlCommand(query))
             {
                 cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
                 cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype;
                 cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                 cmd.CommandType = CommandType.Text;
                 cmd.Connection = con;
                 con.Open();
                 cmd.ExecuteNonQuery();
                 con.Close();
             }
         }
         lblMessage.ForeColor = Color.Green;
         lblMessage.Text = "File Uploaded Successfully";
         Response.Redirect(Request.Url.AbsoluteUri);
     }
          
     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
     {
        
             DataTable dt = (DataTable)ViewState["Data"];
             int index = Convert.ToInt32(e.RowIndex);
             // Delete from ViewState.
             dt.Rows[index].Delete();
             ViewState["Data"] = dt;
             if (GridView1.DataKeys[e.RowIndex].Value != DBNull.Value)
             {
                 int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
                 // Delete from Database.
                 string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                 using (SqlConnection con = new SqlConnection(constr))
                 {
                     string query = "DELETE FROM tblFiles WHERE Id = @Id";
                     using (SqlCommand cmd = new SqlCommand(query))
                     {
                         cmd.Connection = con;
                         cmd.Parameters.AddWithValue("@Id", id);
                         con.Open();
                         cmd.ExecuteNonQuery();
                         con.Close();
                     }
                 }
             }
      
             BindGridView();
         
     }
          
     private void BindGridView()
     {
         string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
         using (SqlConnection con = new SqlConnection(constr))
         {
             string query = "SELECT Id, Name, Data FROM tblFiles";
             using (SqlCommand cmd = new SqlCommand(query))
             {
                 cmd.Connection = con;
                 SqlDataAdapter sda = new SqlDataAdapter(cmd);
                 DataTable dt = new DataTable();
                 sda.Fill(dt);
                 ViewState["Data"] = dt;
                 GridView1.DataSource = dt;
                 GridView1.DataBind();
             }
         }
     }
    
    CREATE TABLE [dbo].[tblFiles] (
        [Id]          INT             IDENTITY (1, 1) NOT NULL,
        [Name]        VARCHAR (50)    NULL,
        [ContentType] VARCHAR (100)   NULL,
        [Data]        VARBINARY (MAX) NULL
    );
    

    16

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.