locked
Upload multiple files and show in gridview? RRS feed

  • Question

  • User481677910 posted

    Hi,

    Is this possible to upload multiple files and then show it on gridview?

    Currently I am uploading multiple file using single upload id and it stores in folder.

    HttpFileCollection uploadedFiles = Request.Files;
            int i = uploadedFiles.Count;
            if (i > 0)
            {
                for (int j = 0; j < i; j++)
                {
                    HttpPostedFile userPostedFile = uploadedFiles[j];
    
                    userPostedFile.SaveAs(Server.MapPath("~/images" + fu + Path.GetFileName(userPostedFile.FileName)));
                    FileUpload1.Visible = true;
                    lblUpload.Text = "File(s) uploaded Successfully";

    It's uploading multiple files but how to show these all multiple files download path in gridview? I tried and it's only showing 1 file download path.

    Sunday, September 15, 2019 6:11 PM

Answers

  • User288213138 posted

    Hi Hi new2world2015,

    It's showing file name, file path but image does not store in that path in real. I went to the folder as I define "image" folder there was nothing in it after I uploaded a picture.

    Do you want to save the uploaded file in server folder ?

    if so, you can try below code:

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT * FROM Test51";
                        cmd.Connection = con;
                        con.Open();
                        GridView1.DataSource = cmd.ExecuteReader();
                        GridView1.DataBind();
                        con.Close();
                    }
                }
            }
    
            protected void Upload(object sender, EventArgs e)
            {
                foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
                {
                    string filename = Path.GetFileName(postedFile.FileName);
              
                    string filePath = Server.MapPath(filename);
    
                   
                   if (FileUpload1.PostedFile != null)
    {
    string folder = Server.MapPath("~/Doc/");
    FileUpload1.PostedFile.SaveAs(Path.Combine(folder, filename));
    } string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into Test51 values (@Name, @Path)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@Path", filePath); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } Response.Redirect(Request.Url.AbsoluteUri); }

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 17, 2019 9:55 AM

All replies

  • User409696431 posted

    Show us the code you tried that only shows one file.  My guess it that there is a logic error where you are not saving each value in your for loop, and only grabbing the last one.  But that's just a guess until we see what you tried.

    Sunday, September 15, 2019 7:09 PM
  • User481677910 posted

    Show us the code you tried that only shows one file.  My guess it that there is a logic error where you are not saving each value in your for loop, and only grabbing the last one.  But that's just a guess until we see what you tried.

    protected void Upload_Click(object sender, EventArgs e)
    { var fu = FileUpload1.FileName; var sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["userConnectionString"].ConnectionString); var cmd = new SqlCommand("UPDATE customer_Order SET Design='" + fu + "', Designpath='" + fu + "' WHERE Order_Name='" + u.Quote_Name + "'", sc); cmd.Parameters.AddWithValue("@design", fu); cmd.Parameters.AddWithValue("@designpath", "~/images" + fu); HttpFileCollection uploadedFiles = Request.Files; int i = uploadedFiles.Count; if (i > 0) { for (int j = 0; j < i; j++) { HttpPostedFile userPostedFile = uploadedFiles[j]; userPostedFile.SaveAs(Server.MapPath("~/images" + fu + Path.GetFileName(userPostedFile.FileName))); FileUpload1.Visible = true; lblUpload.Text = "File(s) uploaded Successfully"; } } cmd.CommandType = CommandType.Text; cmd.Connection = sc; try { sc.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Response.Write(ex.Message); } finally { sc.Close(); sc.Dispose(); Response.Write("Your file has been uploaded"); } } }

    Uploading work just fine but in gridview only one upload file is showing

    gridview code

     <asp:DetailsView ID="DetailsView1" runat="server" 
               BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" 
                 CellPadding="2" ForeColor="Black" Height="17px" Width="539px" 
                 Font-Names="Verdana" Font-Size="Medium" style="font-size: small" 
                Font-Bold="True" onpageindexchanging="DetailsView1_PageIndexChanging" AutoGenerateRows="False">
                 <AlternatingRowStyle BackColor="PaleGoldenrod" />
                <AlternatingRowStyle BackColor="PaleGoldenrod" />
                <CommandRowStyle Font-Size="Small" />
                <EditRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                <FooterStyle BackColor="Tan" />
                <HeaderStyle BackColor="Tan" Font-Bold="True" Font-Names="Verdana" />
                <PagerStyle BackColor="PaleGoldenrod" Font-Names="Verdana" Font-Size="Small" 
                    ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
    
    
    <Fields>
        <asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" />
        <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
        <asp:BoundField DataField="Order_Name" HeaderText="Order_Name" SortExpression="Quote_Name" />
    
       
         <asp:HyperLinkField HeaderText="Download File 1" DataNavigateUrlFields="Design" DataNavigateUrlFormatString="/images1/{0}" DataTextField="Design" />    
         
         
           </Fields>
    
             </asp:DetailsView>

    Sunday, September 15, 2019 11:50 PM
  • User-1716253493 posted

    Hi,

    While upload iteration, use insert/update data in success part of try catch. Use it to count success/fail files also, next time show it in lblUpload after iteration.

    You can also use new datatable as gv datasource, use success part to insert row

    After iteration, bind the gridview using the dt or get it from db based some value like upload datetime

    I sugest to store file name only to the db, use format string for hyperlinkfield url like

    DataNavigateUrlFields="Design" DataNavigateUrlFormatString="~/images/{0}"
    Monday, September 16, 2019 12:39 AM
  • User409696431 posted

    You are not saving each file into the database, you are only saving one name.

    It is not clear if you want multiple lines in the database, each with one file, or one line, with one column containing multiple filenames, but whichever it is, you need the logic to use the names inside the for loop (userPostedFile.FileName).

    If you want all the file names in one column, append each filename to a string and use that to update the field after the for loop completes.  Your gridview is assuming only one file, from the code you showed us.

    Can you clarify what you are actually trying to display?

    Monday, September 16, 2019 1:03 AM
  • User288213138 posted

    Hi new2world2015,

    Upload multiple files and show in gridview

    You say you show GridView, but your post code is DetailsView.

    WHERE Order_Name='" + u.Quote_Name +

    And According to your description, i can't reproduce your problem, but i made demo for you.

    Loop through all uploaded files and get the file name of each file. Note that you need to get the path to the file based on each file.

    The code:

    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
                <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
                <hr />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="File Name" />
                        <asp:BoundField DataField="Path" HeaderText="Path" />
                    </Columns>
                </asp:GridView>
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT * FROM Test51";
                        cmd.Connection = con;
                        con.Open();
                        GridView1.DataSource = cmd.ExecuteReader();
                        GridView1.DataBind();
                        con.Close();
                    }
                }
            }
    
            protected void Upload(object sender, EventArgs e)
            {
                foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
                {
                    string filename = Path.GetFileName(postedFile.FileName);
    string filePath = Server.MapPath(filename);

    //string filePath = Server.MapPath(FileUpload1.FileName); This displays only one file path string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into Test51 values (@Name, @Path)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@Path", filePath); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } Response.Redirect(Request.Url.AbsoluteUri); }

    The result:

    Best regards,

    Sam

    Monday, September 16, 2019 3:27 AM
  • User481677910 posted

    Hi new2world2015,

    new2world2015

    Upload multiple files and show in gridview

    You say you show GridView, but your post code is DetailsView.

    new2world2015

    WHERE Order_Name='" + u.Quote_Name +

    And According to your description, i can't reproduce your problem, but i made demo for you.

    Loop through all uploaded files and get the file name of each file. Note that you need to get the path to the file based on each file.

    The code:

    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
                <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
                <hr />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="File Name" />
                        <asp:BoundField DataField="Path" HeaderText="Path" />
                    </Columns>
                </asp:GridView>
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT * FROM Test51";
                        cmd.Connection = con;
                        con.Open();
                        GridView1.DataSource = cmd.ExecuteReader();
                        GridView1.DataBind();
                        con.Close();
                    }
                }
            }
    
            protected void Upload(object sender, EventArgs e)
            {
                foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
                {
                    string filename = Path.GetFileName(postedFile.FileName);
    string filePath = Server.MapPath(filename);

    //string filePath = Server.MapPath(FileUpload1.FileName); This displays only one file path string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into Test51 values (@Name, @Path)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@Path", filePath); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } Response.Redirect(Request.Url.AbsoluteUri); }

    The result:

    Best regards,

    Sam

    Thank you this is exactly what I needed. Admin can upload the multiple files in specific users submitted order and that specific user can download the files by the clicking on file path.

    I tried above code

    It's showing file name, file path but image does not store in that path in real. I went to the folder as I define "image" folder there was nothing in it after I uploaded a picture.

     

    Monday, September 16, 2019 4:48 PM
  • User409696431 posted

    Your original code shows how to save the file and get the correct path.  (See your code around your SaveAs(Server.MapPath... line.) You need that logic to the sample code you were given.

    Tuesday, September 17, 2019 12:19 AM
  • User288213138 posted

    Hi Hi new2world2015,

    It's showing file name, file path but image does not store in that path in real. I went to the folder as I define "image" folder there was nothing in it after I uploaded a picture.

    Do you want to save the uploaded file in server folder ?

    if so, you can try below code:

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "SELECT * FROM Test51";
                        cmd.Connection = con;
                        con.Open();
                        GridView1.DataSource = cmd.ExecuteReader();
                        GridView1.DataBind();
                        con.Close();
                    }
                }
            }
    
            protected void Upload(object sender, EventArgs e)
            {
                foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
                {
                    string filename = Path.GetFileName(postedFile.FileName);
              
                    string filePath = Server.MapPath(filename);
    
                   
                   if (FileUpload1.PostedFile != null)
    {
    string folder = Server.MapPath("~/Doc/");
    FileUpload1.PostedFile.SaveAs(Path.Combine(folder, filename));
    } string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into Test51 values (@Name, @Path)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@Path", filePath); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } Response.Redirect(Request.Url.AbsoluteUri); }

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 17, 2019 9:55 AM
  • User-2054057000 posted

    How to Upload Multiple files using jQuery AJAX in ASP.NET MVC will help you, download the source codes and check how they are working. Once the files are uploaded all you have to do is to bind them with GridView. I would suggest you to just refresh your page (location.reload();) and bind the GridView in !Page.isPostback 

    private void Page_Load()
    {
        if (!IsPostBack)
        {
            // bind your GridView
        }
    }

    Thanks and regards

    Friday, September 20, 2019 9:38 AM