Persist FileUpload Control Value

前端 未结 3 1195
渐次进展
渐次进展 2020-11-30 10:21

I have asp.net FileUpload control inside an update panel. When I click upload button, I am reading the file for some code, if code not found then I am showing ModalPopup for

3条回答
  •  半阙折子戏
    2020-11-30 10:56

    Background:: When a file is selected using FileUpload Control ,then on postback, PostedFile property gets initialized with HttpPostedFile object for the file. Since http request cannot maintain state, so it looses it's state.

    NOTE: FileUpload control will not work with asynchronous postback.So a postback is needed to get the file. One way is to set the triggers for your Upload button, i.e. & NOT

     
          
          
          
          
          
              
          
     
    

    And your Upload button code:

     protected void btnUpload_Click(object sender, EventArgs e)
         {
            if (fileUpload1.HasFile)
            {                
                fileName = fileupload1.FileName;
                fileUpload1.SaveAs("~/UploadedContent/" + fileName);
            }
         }
    

    TO PERSIST THE VALUE OF FILEUPLOAD CONTROL, you can store the fileupload object altogether in session and after postback retrieve the values you require from session.

    protected void Page_Load(object sender, EventArgs e)
        {
            // store the FileUpload object in Session. 
            // "FileUpload1" is the ID of your FileUpload control
            // This condition occurs for first time you upload a file
             if (Session["FileUpload1"] == null && FileUpload1.HasFile)  
               { 
                Session["FileUpload1"] = FileUpload1; 
                Label1.Text = FileUpload1.FileName; // get the name 
               }
            // This condition will occur on next postbacks        
            else if (Session["FileUpload1"] != null && (! FileUpload1.HasFile)) 
              { 
                FileUpload1 = (FileUpload) Session["FileUpload1"]; 
                Label1.Text = FileUpload1.FileName; 
              } 
         //  when Session will have File but user want to change the file 
         // i.e. wants to upload a new file using same FileUpload control
         // so update the session to have the newly uploaded file
            else if (FileUpload1.HasFile) 
             { 
                Session["FileUpload1"] = FileUpload1; 
                Label1.Text = FileUpload1.FileName; 
             }
         }
    

提交回复
热议问题