Search This Blog

Wednesday

File Upload is not working with updatepanel - Asp.net C#

By: Mohammad Tuaha

Problem:
File upload is not working with updatepanel + asp.net, C#. or
i can't upload image for ajax updatepanel.

Solution:
 Add this line is not properly work in every time in Page load
    Page.Form.Attributes.Add("enctype", "multipart/form-data");

    protected void Page_Load(object sender, EventArgs e)
    {
       Page.Form.Attributes.Add("enctype", "multipart/form-data");
    }

Best Solution:
If you are using updatepanel in  master page no problem u have to use another updatepanel with different ID. Just u have to use
Add the trigger for the UpdatePanel and give the ControlID.  
       Triggers  asp:PostBackTrigger   ControlID="Button1"   /Triggers

 Please follow the code below
Default.aspx page
=====================================
 

Default.aspx.cs page
==========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class AddImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       // Page.Form.Attributes.Add("enctype", "multipart/form-data");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);

        if (FileUpload1.HasFile)
        {
            if (extension == ".png")
            {
                string strPath = MapPath("User_Photo/") + fileName + extension;
                FileUpload1.SaveAs(strPath);
                 lblmessage.Text = "Successfully Saved";
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Only .Png Format can be support')", true);
            }
        }
      
    }
}

Download Project


2 comments:

  1. Nikolus: (USA)
    Very helpful content.

    ReplyDelete
  2. Oh my boss you solved my problem.

    ReplyDelete

Thanks for your opinion