Header Ads

Upload Images using C#, ASP.NET 2.0 and AJAX feature

Introduction:
I worked earlier to upload the images which can be viewed from some other pages. But, When I was thinking about uploading an image without doing any server side post back, planned to write this article. In this article I will demonstrate how to create a simple page that allows you to upload and be able to view it without doing any server side post back.

Idea:
First we need a page which allows the user to select the image to upload. Once the user has selected the file, the image will be uploaed into the server’s folder and return the URL to display the image. Assign the returned image URL into the image which we need to display.

Uploading the image from Client to the Server by using Callback:
The uploading of the image is performed by using ASP.net 2.0 Client Callbacks. Let’s look at in more detail.

1. Place the image control, and file upload control, and the text box which gives the option to enter the file name to be saved.








2. Once the user selects the file to upload, "onChange" event for the file control will be triggered. On result of this, the UpoadMenuItemImage(this) will be called. “this” is a parameter which is passed as current object to the method.

function UploadMenuItemImage(obj)
{
//-- Upload the image to the server folder
var filePath = obj.value;
var desiredFileName = document.getElementById("desiredFileName").value;

// Calls the JS Method to pass the Image Object Value to the SERVER.
// Note: The definitition for the funtion, "RequestServer" will be rendered from the Server.
RequestServer(desiredFileName + "|" + obj.value, 'ImageUpload');
}


3. "RequestServer()" is a method which invokes the server-side method “RaiseCallbackEvent()” at Serverside. The syntax of this method is, RequestServer(, ). The function definition for the RequestServer method will be rendered from Server Side Page Load Event. let's discuss later of this article.

//-- This is a method which should be implemented since the page class implements ICallbackEventHandler.
//-- This will be called automatically Once the XMLHttp Request sent to the Server.
public void RaiseCallbackEvent(string eventArgument)
{
if (!String.IsNullOrEmpty(eventArgument))
{
strArgument = eventArgument;
}
}


4. The Value(first argument) which is passed from RequestServer() method to the Server, can be accessed as eventArgument in RaiseCallbackEvent method which is defined in Server. This eventArgument is assigned into global variable which can be accessed from any where in the class, and it triggers another method called GetCallbackResult().

This method should be implemented since the page class implements ICallbackEventHandler.
public string GetCallbackResult()
{
string strResult = string.Empty;

string[] strData = strArgument.Split("|".ToCharArray());

//-- 1. strData[0] => desired fileName; strData[1] => file content.
strResult = UploadMenuImage(strData[0], strData[1]);

return strResult;
}


5. You might think, why we are implementing these two methods, "RaiseCallbackEvent(arg)", and "GetCallbackResult()". Right..? If you want the Callback feature to be implemented on the page, The Page Class should implement the interface, "ICallbackEventHandler".

public partial class ImageUpload : System.Web.UI.Page, ICallbackEventHandler

The definition of the interface ICallbackEventHandler is:

namespace System.Web.UI
{
//-- Used to indicate that a control can be the target of a callback event to the server.
public interface ICallbackEventHandler
{
//-- Returns the results of a callback event that targets a control.
string GetCallbackResult();

//-- Processes a callback event that targets a control.
//-- eventArgument: A string that represents an event argument to pass to the event handler.
void RaiseCallbackEvent(string eventArgument);
}
}


6. GetCallbackResult() method extracts the parameter which is passed by RequestServer() method, parse the Values, and call the method to upload the image. Once it is uploaded, which returns the URL of the image is stored in a server-sider folder. Okay, where is the Code to store the image into the Server Folder..? mmm... Check it out.

private string UploadMenuImage(string strNewFileName, string strFileName)
{
string imageFileName = strNewFileName;
string fileName = System.IO.Path.GetFileName(strFileName);
string path = Server.MapPath("UploadedImages/");
string fullPath = path + imageFileName + System.IO.Path.GetExtension(strFileName);
string strURL = Request.Url.ToString();
strURL = strURL.Replace("ImageUpload.aspx", "");
string returnPath = strURL + "UploadedImages/" + imageFileName + System.IO.Path.GetExtension(strFileName);

try
{
//-- Read the file Content which will be uploaded.
Stream s = File.OpenRead(strFileName);
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, (int)s.Length);
int len = (int)s.Length;
s.Dispose();
s.Close();

//-- Create a file in Stream.
FileStream fs = new FileStream(fullPath, FileMode.Create);
fs.Write(buffer, 0, len);

//-- Save stream as Image.
Bitmap bmp = new Bitmap(fs);
if (System.IO.Path.GetExtension(strFileName).Equals(".gif"))
{
bmp.Save(fs, ImageFormat.Gif);
}
else
{
bmp.Save(fs, ImageFormat.Jpeg);
}

bmp.Dispose();

fs.Dispose();
fs.Close();

}
catch (Exception objException)
{ }

//-- Return the Image path.
return returnPath;
}


7. From this above method, we got the URL to be assigned to the image control. but, now we need the Javascript function to be invoked and that should have this url value as a parameter to assign the source for the image to display. right..? How to do that..?

protected void Page_Load(object sender, EventArgs e)
{
//-- Obtains a reference to a client-side function that
//-- when invoked, initiates a client call back to a server-side event.
//-- The client-side function for this includes a specified control, argument, client-side script, and context.
string callBack = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");

//-- JS function definition
string clientFunction = "function RequestServer(arg, context){ " + callBack + "; }";

//-- Render the function definition if it is not rendered before.
if (!ClientScript.IsClientScriptBlockRegistered("RequestServer"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RequestServer", clientFunction, true);
}
}


8. So, Whatever the value is returned from the method, GetCallbackResult() can be accessed at client-side as the variable, called, "result". Context is a parameter which is useful to identify from which request this process is being triggered.
Note: "ReceiveServerData()" is a method which will be invoked with the parameter value of result, and the context.

//-- This is a method which will be called from Callback handler.
//-- According to the context, the corresponding function will be invoked.
function ReceiveServerData(result, context)
{
// Do manipulation whatever you want to do the return Value from the Server.
alert(result);
document.getElementById("imgMenuItem").src = result;
}

That’s it. Get the image url from the parameter called result, assign it with image control.

Conclusion:
I hope this article is useful for you guys. You can download the code to experiment on this.
You can play around this. if there is a need to send some other call back request to the server, still you can do that by differentiating context information.
Enjoy Coding..!

No comments:



Powered by Blogger.