How to assign value from session upload file into upload posted file again

BeUnique 2,112 Reputation points
2024-05-31T18:44:51.0666667+00:00

i am trying to save uploaded file after some big process.

i am saving uploaded file in session to retain the file upload data.

i.e : uploaded file will be saving into session variable. after saving to session upload file will be cleared. but, the upload file name will saved into session.

when i am saving the below code i used. ut, i am getting error.

FileUpload FileUpload1 = null;

FileUpload1 = (FileUpload)Session["FileUpload1"]; //

//Save file with re-named file.

            SaveFile(FileUpload1, Path);
``````aspx-csharp
 private void SaveFile(FileUpload fileupload, string path)
        {
            fileupload.PostedFile.SaveAs(path);
            const int numberOfRetries = 10;
            const int delayOnRetry = 1000;

            for (int i = 1; i <= numberOfRetries; ++i)
            {
                try
                {
                    fileupload.PostedFile.SaveAs(path);
                    break;
                }
                catch (IOException e) when (i <= numberOfRetries)
                {
                    Thread.Sleep(delayOnRetry);
                }
            }
            fileupload.Dispose();
        }

User's image

how to save the session value file into database...?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,417 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 28,841 Reputation points Microsoft Vendor
    2024-06-03T03:42:53.8133333+00:00

    Hi @Gani_tpt,

    If you insist on using session, you can refer to the following example.

    One thing to note is that in order to prevent users from forgetting to click the "Upload" button, I have added code in the example to upload the file using the FileUpload control without clicking the "Upload" button.

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
     <script type="text/javascript">
         function UploadFile(fileUpload) {
             if (fileUpload.value != '') {
                 $("[id*=gvCustomers]").find("[id*=Button1]").click();
             }
         }
     </script>
    
     <asp:FileUpload ID="fuUpload" runat="server" />
     <asp:Label ID="ImageErrorLabel" runat="server" />
     <asp:Button ID="Button1" Text="Upload" OnClick="Upload" runat="server" Style="display: none" />
    
    protected void Page_Load(object sender, EventArgs e)
    {
        Control control = null;
        DropDownList DropDownList1 = null;
        if (!this.IsPostBack)
        {
            this.BindGrid();
            if (gvCustomers.FooterRow != null)
            {
                control = gvCustomers.FooterRow;
                DropDownList1 = (control.FindControl("ddlCustomers") as DropDownList);
            }
            else
            {
                control = gvCustomers.Controls[0].Controls[0];
                DropDownList1 = (control.FindControl("ddlCustomer") as DropDownList);
            }
            FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
            fuUpload.Attributes["onchange"] = "UploadFile(this)";
            List<Item> items = new List<Item>();
            items.Add(new Item() { Value = "1", Text = "USA" });
            items.Add(new Item() { Value = "2", Text = "UK" });
            items.Add(new Item() { Value = "3", Text = "AUS" });
            items.Add(new Item() { Value = "4", Text = "OTHERS" });
            DropDownList1.DataSource = items;
            DropDownList1.DataTextField = "Text";
            DropDownList1.DataValueField = "Value";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, new ListItem("--Select --", "0"));
        }
        if (this.IsPostBack)
        {
            if (gvCustomers.FooterRow != null)
            {
                control = gvCustomers.FooterRow;
            }
            else
            {
                control = gvCustomers.Controls[0].Controls[0];
            }
            Label label = (control.FindControl("ImageErrorLabel") as Label);
            FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
            if (Session["FileUpload1"] == null && fuUpload.HasFile)
            {
                Session["FileUpload1"] = fuUpload.PostedFile;
                label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
            }
            else if (Session["FileUpload1"] != null && (!fuUpload.HasFile))
            {
                HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
                label.Text = Path.GetFileName(file.FileName);
            }
            else if (fuUpload.HasFile)
            {
                Session["FileUpload1"] = fuUpload.PostedFile;
                label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
            }
        }
    }
    protected void Upload(object sender, EventArgs e)
    {
        Control control = null;
        if (gvCustomers.FooterRow != null)
        {
            control = gvCustomers.FooterRow;
        }
        else
        {
            control = gvCustomers.Controls[0].Controls[0];
        }
        Label label = (control.FindControl("ImageErrorLabel") as Label);
        FileUpload fuUpload = (FileUpload)control.FindControl("fuUpload");
        if (Session["FileUpload1"] == null && fuUpload.HasFile)
        {
            Session["FileUpload1"] = fuUpload.PostedFile;
            label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
            HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
            SaveFile(file);
        }
        else if (Session["FileUpload1"] != null && (!fuUpload.HasFile))
        {
            HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
            label.Text = Path.GetFileName(file.FileName);
            SaveFile(file);
        }
        else if (fuUpload.HasFile)
        {
            Session["FileUpload1"] = fuUpload.PostedFile;
            label.Text = Path.GetFileName(fuUpload.PostedFile.FileName);
            SaveFile(fuUpload.PostedFile);
        }
    }
    private void SaveFile(HttpPostedFile file)
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath("~/images/" + fname));
    }
    

    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.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2024-05-31T20:04:20.6466667+00:00

    you can not save the PostedFile object in session as its disposed on request end. you need to read the file stream into a byte buffer (array), and save the buffer.