I'm trying by means of a FileUpload control and and "Apply" button, brwosong
my local folders for a picture file loading (Apply button) and displayingthe
(local) picture (jpg, gif, ..) file. I don't want the local file to be saved
on the server but displayed on my webform and if ok be stored in my database
together with other related info.
I googled and found some example .. but not exactly what i want to achieve.
Anyone can give me a hint where to start?
An approach is when the user clicks the Submit or Preview button, the
file gets posted to the server, you temporarily store the file in
Session. On the same page, you have an Image control and you set its
ImageUrl property to an ASHX handler page that will serve the image to
the client. In the ASHX page, you get the file out of session, send
it to the client and clear the file out of session. All this is done
within a couple of seconds so the image doesn't stick around in
session very long. Here's some sample code that does this:
// ASPX page code-behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fuTest.HasFile)
{
string contentType = fuTest.PostedFile.ContentType;
if (contentType.StartsWith("image/"))
{
Session["uploadFile"] = fuTest.FileBytes;
imgPreview.Visible = true;
imgPreview.ImageUrl = "image_preview.ashx";
}
}
}
// image_preview.ashx
<%@ WebHandler Language="C#" Class="image_preview" %>
using System;
using System.Web;
using System.Web.SessionState;
public class image_preview : IHttpHandler, IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
byte[] img = (byte[])context.Session["uploadFile"];
if (img != null)
{
context.Response.ContentType = "image";
context.Response.OutputStream.Write(img, 0, img.Length);
// clear session
context.Session["uploadFile"] = null;
}
}
public bool IsReusable {
get {
return false;
}
}
}