3

i have a fileupload control in asp.net, used to upload images. i want to show preview the image in image control of asp.net. here is the aspx code

C# code behind

 protected void Btn_Preview_Click(object sender, EventArgs e)
        {
            try
            {
                if (FU_Img.HasFile)
                {
                    string path = Server.MapPath("/TempImages");

                FileInfo oFileInfo = new FileInfo(FU_Img.PostedFile.FileName);
                string fileName = oFileInfo.Name;

                string fullFileName = path + "//" + fileName;
                string imagePath = "/TempImages/" + fileName;

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                Session["FileUpload"] = FU_Img;
                FU_Img.PostedFile.SaveAs(fullFileName);
                Img_Prof.ImageUrl = imagePath;
            }
        }
        catch (Exception ex)
        {
            using (StreamWriter sw = new StreamWriter("/log.txt"))
            {
                sw.NewLine = DateTime.Now.ToString() + "--->>" + ex.ToString() + "\n" + ex.StackTrace.ToString();
            }
        }
    }

as you can see, i am putting my image control in session. it works fine on development server. when i posted the site to domain i get the issue

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

Stack Trace

[SerializationException: Type 'System.Web.UI.WebControls.FileUpload' in Assembly 'System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.]
   System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +7738443
   System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +258
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +111
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +422
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +51
   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +410
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +134
   System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1577

[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
   System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1662
   System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +34
   System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +606
   System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +239
   System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length) +72
   System.Web.SessionState.OutOfProcSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +87
   System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +560
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75`

here is my web.config

<sessionState mode="InProc"
                    cookieless="true"
                    timeout="20"/>

after i preview my page, i click on update bnutton, and it does nothing. not even Redirect to the other page. Here is my submit button code

 if (Session["FileUpload"] != null && (!FU_Img.HasFile))
            {
                FU_Img = (FileUpload)Session["FileUpload"];
            }
UserOthers UO = new UserOthers();
            if (FU_Img.HasFile)
            {
                try
                {
                    string Photofilename = Path.GetFileName(FU_Img.FileName);
                    Photofilename = Photofilename.Split('.')[1].ToString();
                    String PathFolder = Server.MapPath(Request.ApplicationPath + @"\upload\u" + Session["UserID"].ToString ());
                    if (!Directory.Exists(PathFolder))
                    {
                        Directory.CreateDirectory(PathFolder);
                    }
                    FU_Img.PostedFile.SaveAs(Server.MapPath(Request.ApplicationPath + @"\upload\u" + Session["UserID"].ToString () + "\\image." + Photofilename));
                    UO.Image = @"/upload/u" + Session["UserID"].ToString () + "/image." + Photofilename;
                }
                catch (Exception ex)
                {
                    //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
 con.update_Pic_Vid(UO, Session["UserID"].ToString ());
            Response.Redirect("/AccountSettings.aspx");

Please tell me what wrong i am doing.

Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
  • 1
    Why are you trying to hold your `FileUpload` control in `Session`? Is there any reason you can't just hold the `byte[]` in `Session`? – Mike Perrenoud Mar 22 '13 at 12:20
  • actually i am previewing the image. if Preview button is clicked, fileupload button did not keep the data. so to keep its state, i am keeping that in session so i can submit the file if user is happy with the current prewview. – Saghir A. Khatri Mar 22 '13 at 12:22
  • 1
    I understand that, but you don't need to hold the entire control, just hold the `byte[]` that's posted on the first post back. – Mike Perrenoud Mar 22 '13 at 12:40

2 Answers2

4

Give a look to this post:

you can convert your stream from the fileupload in this way using the ReadFully function posted in the link above:

 var byteArray = ReadFully( FU_Img.PostedFile.InputStream ) ;
 Session["FileUpload"] = byteArray;

and then in your upload function u can change the code to this:

byte[] fileUpload = null;

if (Session["FileUpload"] != null  )
{
   fileUpload = Session["FileUpload"] as byte[];
}

and then save the stream of byte to the disk or to the database.

Community
  • 1
  • 1
codingadventures
  • 2,924
  • 2
  • 19
  • 36
1

Storing a Control in session is not the correct approach. As your Stack Trace points out "FileUpload" is not marked as serializable.

You store the image on disk and store the path to that image in the session and reuse it further.

Th 00 mÄ s
  • 3,776
  • 1
  • 27
  • 46