简体   繁体   中英

how to show an image in an image field by a button click event in c# asp.net

I have a problem to change imageUrl of an image field. i want to show the uploaded image by clicking a button named "upload". here is my server side code:

if (fileUpload.HasFile)
{           Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/uploads/logo"));
            string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
            string targetPath = Path.Combine(targetFolder, "photo.png");
            fileUpload.SaveAs(targetPath);
            employeeImage.ImageUrl = targetPath;
}

I solve this by using webhandler(.ashx).

public class   ImageHandler:IHttpHandler,System.Web.SessionState.IRequiresSessionState

{

  public void ProcessRequest (HttpContext context) {
    //Checking whether the imagebytes variable have anything else not doin anything
    if ((context.Session["ImageBytes"]) != null)
    {
        byte[] image = (byte[])(context.Session["ImageBytes"]);
        context.Response.ContentType = "image/JPEG";
        context.Response.BinaryWrite(image);
    }
}

public bool IsReusable {
    get {
        return false;
    }
}

}

and server side code is:

protected void uploadButton_Click(object sender, EventArgs e)
{
    Session["ImageBytes"] = fileUpload.FileBytes;
    employeeImage.ImageUrl = "~/ImageHandler.ashx";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM