Click here to Skip to main content
15,888,025 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi

I am working on a project and stuck in a scenario. It goes like

I am uploading an image from WebCam and asp.Net File Upload Control in a asp.net page.
I am converting the image into Byte Array and storing it in Database SQL.

Now we need to display all images in a grid View and writing the byte array as Image into temp folder of Project Directory. Now I want to delete my temporary files when I am leaving my Page.

Where Should I code for this (on which event of Page)
Any help would be appreciated.
Posted
Updated 11-Jan-12 20:45pm
v2

you can place the images in a folder and reference them, but deleting them when the user leaves the page is the tricky part.

I would recommend you to create a page that will return the images directly from the database. You should store them as jpeg or png for performance.

Then create a page called getimage.aspx or something. and there in the Page_Load event, return the image (given that you use an ID or something to retrieve the bytes) something like getimage.aspx?imageid=123 for example.

Lets say you got the id, and get the stream from the database, just write the bytes to the Response.OutputStream

C#
Response.Clear();
Response.ContentType = "image/jpeg";
var downloadName = HttpUtility.UrlEncode("imagenameyouwant.jpg", System.Text.Encoding.UTF8);
Response.AppendHeader("content-disposition", string.Format("attachment;filename={0}{1}", downloadName, ext));
Bufferer.Send(input, Response.OutputStream, 4096);
input.Close();
Response.Flush();
Response.End();


the bufferer is a helper class I use to send the content in fragments. here is the code for the Bufferer.Send method:

C#
public static void Send(Stream InputBuffer, Stream OutputBuffer, int bufferSize)
   {
       if (InputBuffer == null) throw new Exception("Input buffer can not be null");
       if (InputBuffer.Position != 0)
           InputBuffer.Position = 0;

       byte[] bytes = new byte[bufferSize];
       int numBytes;
       while ((numBytes = InputBuffer.Read(bytes, 0, bufferSize)) > 0)
           OutputBuffer.Write(bytes, 0, numBytes);
   }


This approach has the benefit that you don't need to save (and also not delete) the images, nor use any tmp folder.
 
Share this answer
 
You can't, not reliably. There are events you can get when the user moves to a new page, but that doesn't mean that you will always gets them: what it the users browser crashes, the power fails, or one of several other reasons? Your file will get left behind, and probably never deleted.

Why are you extracting them from the database to files? The only reason I can think of is to make it easy for the user to download them - so why not let the user download the file directly from the database instead? That way, no temporary files are created, so there is nothing to clear up.

What I do is to set a link to an apsx page as the download link:
C#
/// <summary>
/// Add a download file's information to a table row.
/// </summary>
/// <param name="dl"></param>
/// <returns></returns>
private static HtmlTableRow AddDownloadFile(Downloadable dl)
    {
    HtmlTableRow row = new HtmlTableRow();
    // File name
    HtmlTableCell cell = new HtmlTableCell();
    cell.InnerHtml = "<a href=\"FileTransferDownload.aspx?file=" + dl.Id + "\" target=\"_blank\">" + dl.FileName + "</a>";
    row.Cells.Add(cell);
    // Version
    cell = new HtmlTableCell();
    cell.InnerText = dl.Version.ToString();
    row.Cells.Add(cell);
    // Upload date
    cell = new HtmlTableCell();
    cell.InnerText = dl.UploadedOn.ToString();
    row.Cells.Add(cell);
    return row;
    }
And then the page handles the work:
C#
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileTransferDownload.aspx.cs" Inherits="FileTransferDownload" %>

<%
    // Send a download file to the client given the filename.
    string guid = Request.QueryString["file"];
    string fileName = "ERROR";
    byte[] data = new byte[] { 0, 0, 0, 0 };
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon))
        {
        con.Open();
        string strcmd = "SELECT [iD] ,cn.[fileName],[description] ,[dataContent] ,[version] " +
                        "FROM dlContent cn " +

                        "WHERE cn.iD=@ID";
        using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strcmd, con))
            {
            cmd.Parameters.AddWithValue("@ID", guid);
            using (System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader())
                {
                if (r.Read())
                    {
                    fileName = (string) r["filename"];
                    data = (byte[]) r["dataContent"];
                    }
                }
            }
        }
    Response.Clear();
    Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    Response.AddHeader("Pragma", "no-cache");
    Response.AddHeader("Content-Description", "File Download");
    Response.AddHeader("Content-Type", "application/force-download");
    Response.AddHeader("Content-Transfer-Encoding", "binary\n");
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    Response.BinaryWrite(data);
    //Response.WriteFile("wm5ftdata/" + fileName);
    Response.End();
%>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900