Thursday, March 4, 2010

How to load latest image uploaded with the file upload control without hitting refresh button?

How to load latest image uploaded with the file upload control without hitting refresh button?

Problem Scenario:

When we use fixed image url and upload an image file with the same name than the image displayed in the browser remains the same as the old one till we go and refresh the page.

The below depicted code will perform according to the above explained scenario.

[sourcecode language="html"]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="FileUpload_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>Image Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<br />
<asp:Image ID="Image1" ImageUrl="~/FileUpload/file1.jpg" runat="server" />
</div>
</form>
</body>
</html>
[/sourcecode]
[sourcecode language="csharp"]
using System;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

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

}

protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = string.Concat(Server.MapPath("file1.jpg"));

if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(filePath);
}
}
}
[/sourcecode]

Solution:

Now to approach this kind of situation their are basically two thing that can be done.

1) Rather than just fixing the image url path of image in .aspx page make the path associated to it in the code behind page as well. Like shown in the below sample code.

[sourcecode language="csharp"]

protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = string.Concat(Server.MapPath("file1.jpg"));

if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(filePath);
}

Image1.ImageUrl = filePath;
}

[/sourcecode]

OR

2) If you are changing the image url from javascript than just append time or any random number as a part of query string to the image url. Appending the time after the image path will make it treat as a separate request in IIS and the image will be perfectly loaded.

[sourcecode language="html"]

<a href="http://localhost/MyArticles/FileUpload/file1.jpg?t=11/7/2009%204:25:23%20PM">http://localhost/MyArticles/FileUpload/file1.jpg?t=11/7/2009%204:25:23%20PM</a>

[/sourcecode]

or

[sourcecode language="html"]

http://localhost/MyArticles/FileUpload/file1.jpg?t=63245

[/sourcecode]