ASP.NET - How to select multiple images using FileUpload control

Asked By Chinnarasu Chinnarasu.M on 25-Jun-11 07:28 AM
select multiple images using FileUpload control and any others ideas please give examples.....anybody help me.....
Bala Marish replied to Chinnarasu Chinnarasu.M on 25-Jun-11 07:40 AM
refer this code


getImage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
 //TODO: error checking for query string

 if(Session["dsPhotoFiles"] != null)
 {
    DataSet tmpDs = new DataSet();
    tmpDs = (DataSet)Session["dsPhotoFiles"];

    for (int i = 0; i < tmpDs.Tables[0].Rows.Count; i++)
    {
     if (tmpDs.Tables[0].Rows[i]["id"].ToString() == Request.QueryString["id"])
     {
       Response.BinaryWrite((byte[])(tmpDs.Tables[0].Rows[i]["fileBytes"]));
       break;
     }
    }
 }
}

 

Below is now the code for the main page used to upload multiple images.

Default.aspx

This is the code inside the form tag

<div>
   <asp:Label ID="Label1" runat="server" Text="Locate File:" />  
   <asp:FileUpload ID="fileUp" runat="server" />   
   <br />
   <asp:Label ID="Description" runat="server" Text="Description:"></asp:Label>  
   <asp:TextBox ID="txtDesc" runat="server" Width="349px"></asp:TextBox>
   <asp:Button ID="btnAddFile" runat="server" Text="Add File To Upload List"
          onclick="btnAddFile_Click" />
</div>
 
<div>
   <asp:Label ID="lblCurrentFileCount" runat="server"></asp:Label>
   <br />
   <asp:DataList ID="dlPhotoFiles" runat="server" RepeatColumns="10" RepeatDirection="Horizontal">
     <ItemTemplate>
       <asp:Image ID="Image1" runat="server" ImageUrl='<%# string.Format("~/getImage.aspx?id={0}", Eval("id")) %>'
           Width="50" AlternateText='<%# Eval("fileDesc") %>' />
       <br />
       <asp:LinkButton ID="lnkBtnRemovePhoto" runat="server"
              CommandArgument='<%# Eval("id") %>' OnCommand="lnkBtnRemovePhoto_Command">Remove</asp:LinkButton>
     </ItemTemplate>          
    </asp:DataList>
    <br />
</div>
<br />
<div>
   <asp:Button ID="btnUploadFiles" runat="server" Text="Upload File(s)"
           onclick="btnUploadFiles_Click" />
</div>

Default.aspx.cs

This is all of the code behind:

DataSet dsPhotosFiles = new DataSet();

      protected void Page_Init(object sender, EventArgs e)
      {

        if (Session["dsPhotoFiles"] == null)
        {
          this.initPhotoDS();
          Session.Add("dsPhotoFiles", dsPhotosFiles);
        }
        else
        {
          dsPhotosFiles = (DataSet)Session["dsPhotoFiles"];
        }
      }

      protected void btnAddFile_Click(object sender, EventArgs e)
      {

        if (fileUp.PostedFile.ContentLength > 0)
        {
          //TODO: logic for file extension check
          DataRow dr = dsPhotosFiles.Tables[0].NewRow();

          string fileExt = System.IO.Path.GetExtension(fileUp.PostedFile.FileName);

          byte[] imageBytes = new byte[fileUp.PostedFile.InputStream.Length];
          fileUp.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

          dr["fileBytes"] = imageBytes;
          dr["filePath"] = fileUp.PostedFile.FileName;
          dr["fileDesc"] = txtDesc.Text;
          dr["id"] = System.Guid.NewGuid().ToString();

          dsPhotosFiles.Tables[0].Rows.Add(dr);
        }

        this.bindDataList();      

        txtDesc.Text = "";
        lblCurrentFileCount.Text = "Current Files To Upload: " + dsPhotosFiles.Tables[0].Rows.Count;
      }

      protected void btnUploadFiles_Click(object sender, EventArgs e)
      {

        try
        {
          for (int i = 0; i < dsPhotosFiles.Tables[0].Rows.Count; i++)
          {
            //TODO:logic to save image path and description to database
           
            string fileName = System.IO.Path.GetFileName(dsPhotosFiles.Tables[0].Rows[i]["filePath"].ToString());

            byte[] imageBytes;
            imageBytes = (byte[])dsPhotosFiles.Tables[0].Rows[i]["fileBytes"];

            //their is no uploading..just writing out the bytes to the directory on the web server.
            System.IO.File.WriteAllBytes(Server.MapPath(string.Format("~/documents/{0}", fileName)), imageBytes);
          }

          //TODO: show success message logic

          //clear out rows of dataset not the whole dataset
          dsPhotosFiles.Tables[0].Rows.Clear();
          this.bindDataList();
          lblCurrentFileCount.Text = "Current Files To Upload: " + "0";
         
        }
        catch (Exception ex)
        {
          //TODO: show error message of which file did not get uploaded
          throw new Exception(ex.Message);
        }
      
      }

      private void initPhotoDS()
      {
        dsPhotosFiles.Tables.Add("Photos");
        dsPhotosFiles.Tables[0].Columns.Add("fileBytes", Type.GetType("System.Byte[]"));
        dsPhotosFiles.Tables[0].Columns.Add("filePath");
        dsPhotosFiles.Tables[0].Columns.Add("fileDesc");
        dsPhotosFiles.Tables[0].Columns.Add("id");
      }

      private void bindDataList()
      {
        dlPhotoFiles.DataSource = dsPhotosFiles;
        dlPhotoFiles.DataKeyField = "id";
        dlPhotoFiles.DataBind();
      }

      protected void lnkBtnRemovePhoto_Command(object sender, CommandEventArgs e)
      {

        foreach(DataRow dr in dsPhotosFiles.Tables[0].Rows)
        {
          if (dr["id"].ToString() == e.CommandArgument.ToString())
          {
            dsPhotosFiles.Tables[0].Rows.Remove(dr);
            break;
          }

        }

        this.bindDataList();
        lblCurrentFileCount.Text = "Current Files To Upload: " + dsPhotosFiles.Tables[0].Rows.Count;
      }

dipa ahuja replied to Chinnarasu Chinnarasu.M on 25-Jun-11 08:03 AM
<script type="text/javascript">
var counter = 0;
function AddFileUpload()
{
    var div = document.createElement('DIV');
    div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
    document.getElementById("FileUploadContainer").appendChild(div);
    counter++;
}
function RemoveFileUpload(div)
{
    document.getElementById("FileUploadContainer").removeChild(div.parentNode); 
}
</script>
<span style="font-family: Arial">Click to add files</span>  
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

.CS 
protected void btnUpload_Click(object sender, EventArgs e)
{
  for (int i = 0; i < Request.Files.Count; i++)
  {
    HttpPostedFile PostedFile = Request.Files[i];
    if (PostedFile.ContentLength > 0)
    {
      string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
      PostedFile.SaveAs(Server.MapPath("temp\\") + FileName);
    }
  }
}