Click here to Skip to main content
15,944,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Created a gallary Using a FileUploader and Listview control and also use a Http handler.In a browser First I upload a picture using file uploader intodatabase and show it in the page using list view. But When I refresh page using F5 kye after uploading the same image again uploaded into database and shows in the page. How can I prevent this duplicate upload? I use the code as follows.

In default.aspx I use the following code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<link href="MyGallary.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">




Image
<asp:Label ID="lblTags" runat="server" Text="Tags">
         
<asp:TextBox ID="txtTags" runat="server">


<asp:Label ID="lblImage" runat="server" Text="Upload Picture">
    
<asp:FileUpload ID="imgUpload" runat="server"/>
     




<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />
        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF">




<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:albumConnString %>"
SelectCommand="SELECT [pic_id], [picture_tag], [pic] FROM [Album]">




<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" GroupItemCount="4">
<layouttemplate>
<asp:Placeholder
id="groupPlaceholder"
runat="server" />




<%--<asp:DataPager ID="DataPager1" runat="server">
<fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
ShowLastPageButton="True" />

--%>

<grouptemplate>

<asp:Placeholder
id="itemPlaceholder"
runat="server" />


<itemtemplate>
<asp:Image
id="picAlbum" runat="server" AlternateText='<% #Eval("picture_tag") %>'
ImageUrl='<%# "ShowImage.ashx?id=" + Eval("pic_id") %>' Width="240" Height="240" />

<emptyitemtemplate>



                                                                                             
<asp:DataPager ID="DataPagerProducts" runat="server" PagedControlID="ListView1"
PageSize="16" >
<fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowNextPageButton="False" />
<%--<asp:NumericPagerField />--%>
<asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowPreviousPageButton="False" />











</form>
</body>
</html>

In default.aspx.cs file i use the following code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{

SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the picture tag and image into db
string conn = ConfigurationManager.ConnectionStrings["albumConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();

string sql = "INSERT INTO Album(picture_tag,pic) VALUES(@tag,@pic)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@tag", txtTags.Text);
cmd.Parameters.AddWithValue("@pic", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Picture ID is {0}", id);
ListView1.DataBind();

}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}


}
//lblResult.Text = String.Format("Picture ID is {0}", id);
//ListView

}

In Http Handler I use The following Code
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

public class ShowImage : IHttpHandler
{


public void ProcessRequest(HttpContext context)
{
Int32 picid;
if (context.Request.QueryString["id"] != null)
picid = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowAlbumImage(picid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowAlbumImage(int picid)
{
string conn = ConfigurationManager.ConnectionStrings["albumConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT pic FROM Album WHERE Pic_ID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", picid);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}

}
Posted

1 solution

This is somewhat common issue faced.

Have a look at these articles:
Refresh Page Issue in ASP.Net[^]
Stop Refresh after Submitting your Request[^]
Detecting Page Refresh[^]
 
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