FileUpload control loses its content on PostBack

13,474

Solution 1

This is actually security related. Imagine visiting a site with a file upload and the path pre-filled with something like "c:\Users\Meensat\passwords.docx". You hit submit, and they have your passwords.

What you can do on postback is check for a file using the .PostedFile property, and if one exists, save it to a temp file. In Session, store a reference to the temp file, the file name, etc.

EDIT

.PostedFile is actually a property of the FileUpload control.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfile.aspx

That link has sample code showing how to save the file to disk.

Solution 2

There really isn't a way around this due to the way HTTP/Forms work. The file will get submitted on the first post to the server. You could also store the file bytes in ViewState but postbacks will be slow. Your options are to not perform a postback and use javascript or other alternatives to get the same functionality or store the file somewhere on the server (ex: session, temp folder, database).

Share:
13,474
Meensat
Author by

Meensat

Updated on June 05, 2022

Comments

  • Meensat
    Meensat almost 2 years

    I have 3 FileUpload controls. They lose their content when the page PostBack. The page is post back when I click on a button to show some hidden controls.

    what can I do to keep their contents without using session ?

  • Chris
    Chris almost 12 years
    Essentially for anything that you'd change with a postback, you'd do the same with javascript instead so the page only actually posts back once the user has completely filled out the form and the server is ready to accept the file. For example, instead of posting back when a user checks a checkbox to set another fields visibility, you do that with javascript.