Pages

Monday, December 19, 2011

Asynchronous File Upload in Asp.net using C# jquery Uploadify

Hello Readers,
You might have a need for uploading files asynchronously in asp.net using c# with jquery.
here i will give u the best tutorial to do this.
You will need to download the jquery pluggin this.download this pluggin from here.
http://www.uploadify.com/download/
after u download this file extract this folder and rename it to uploadify and put it in the root folder of ur project.
Now crate new aspx page from which we will upload file. name it ImageUploader.aspx(you can give any name)
insert the following code in ur header part of ur file.
?
1
2
3
4
5
6
7
8
9
10
11
12
13









//reference of css file of uploadify, you will find this in the folder uploadify
and then in the body of ur page insert the following code...
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25



Now let's create the handler to receive the httpPostedData.
Add Generic Handler to ur project(Right click on project from solution explorer and then click on add new item.from the given option select Generic Handler). Name it Uploader.ashx
The code for the handler is as below.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

using System;
using System.Web;
using System.Web.SessionState;

public class Uploader : IHttpHandler, IRequiresSessionState
{

public void ProcessRequest (HttpContext context) {
try
{
HttpPostedFile file = context.Request.Files["Filedata"];
int id = (Int32.Parse(context.Request["id"]));//here we are accessing the passed values from the javascript
string filename = id.ToString() + file.FileName;
string filepath = HttpContext.Current.Server.MapPath("~").ToString() + "\\Avatar\\"+filename ;
file.SaveAs(filepath);
//your asp.net logic to save file path in database
context.Response.Write("1");
}
catch (Exception ex)
{
context.Response.Write("0");
}
}

public bool IsReusable {
get {
return false;
}
}

}
It's done just run ur imageupload.aspx page and click on browse button to upload the file.

No comments: