Introduction
Once I was trying to create a page it has two file upload controls and many other fields and around 30 post backs. Once user select files in file upload controls and in any selection when page’s post back event occurs, file upload control loose it’s value. It was very annoying situation for me to maintain the state of FileUpload Control. I search around so many articles and sites but didn't get any fixed solution. Then I decided to do it myself and publish for other developers. This is very common problem with many developers.
About ASP.Net's File Upload Control
File upload control has a text box and a browse button. When a file is selected, on PostBack PostedFile property gets initilized with HttpPostedFile object for the file. As we know that http request can't maintain state, and PostedFile is initilized with HttpPostedFile Object so it loose it's state. PostedFile property can be used to get information about file e.g. ContentLength, Content Type, FileName, InputStream. It has also a method SaveAs to store file on disk. You can read more about it on MSDN. To maintain the length of solution I will focus to code snippet.
How do we Achieve
I have seen so many options available, but many of them are not working or need too much effort. How can we do this with minimal efforts? Idea is Session Object. As we know session object can store any object and in case of OutProc/State Server Serializable Object only. So idea is very simple store fileupload object in session and in the post back get the values back from it. Use this code in Page_Load.
if (Session["FileUpload1"] == null && FileUpload1.HasFile)
{
Session["FileUpload1"] = FileUpload1;
Label1.Text = FileUpload1.FileName;
}
else if (Session["FileUpload1"] != null && (! FileUpload1.HasFile))
{
FileUpload1 = (FileUpload) Session["FileUpload1"];
Label1.Text = FileUpload1.FileName;
}
else if (FileUpload1.HasFile)
{
Session["FileUpload1"] = FileUpload1;
Label1.Text = FileUpload1.FileName;
}
Conclusion
This is very simple and effort less solution. Does not require any extra effort.