views:

678

answers:

2

Hi, I want to store files uploaded by user in session variable,so that i can use it from any page i want in my project.i am retreiving files from statement:

httpFileCollection uploads=HttpContext.Current.Request.Files;

how can i store and retrieve this in session variable??

Thanks in adavnce

+1  A: 

That Files object is limited to the current request; to persist this between requests you need to do something with the uploaded data - either SaveAs, or by reading from the InputStream.

IMO, storing it in session is not a great idea for scalability reasons - it would be more natural, for example, to write the files to a shared scratch area on disk, and store the paths in session.

Marc Gravell
A: 

The same way that you store and retrieve ANY other object into and from Session state:

//Store
Session["UploadedFiles"] = uploads;

//Retrieve
if (Session["UploadedFiles"] != null)
{
  //try-catch blocks omitted for brevity. Please implement yourself.
  HttpFileCollection myUploads = (HttpFileCollection)Session["UploadedFiles"];

  // Do something with the HttpFileCollection (such as Save).

  // Remove the object from Session after you have retrieved it.
  Session.Remove("UploadedFiles");
}

The wisdom of storing this object in Session is quite debatable and I would not recommend it however.

As for the contention (refer your previous question) that the HttpFileCollection variable cannot be stored in Session state, I refute that as I have been able to do it in the past. Once you have retrieved the object into a variable, you can save it however you want.

Cerebrus
Re storing in session state - it depends on which session provider you use. The in-memory provider will probably work, but since the types aren't serializable, and out-of-process storage will fail horribly. So relying on this would be brittle. In particular, you need out-of-process for it to work correctly on a web farm.
Marc Gravell
@Marc: Thanks for your comment. I'm aware of the ramifications of storing such an object in Session and have mentioned it in my answer.
Cerebrus