ASP.NET

Uploading Files using JQuery Ajax in ASP.NET

Simply way we can upload the images from ASP.NET form using Jquery Ajax, User can upload the file to server through Ajax Request to Generic Handler.

Web From: 

JQuery:

$(function () {
$("#btnregister").click(function () {
SaveImage();
});
});

function SaveImage() {
var fileUpload = $("#filepro").get(0);
var files = fileUpload.files;

var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}

$.ajax({
url: "uploadimages.ashx",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (result) { alert(result); },
error: function (err) {
alert(err.statusText)
}
});

evt.preventDefault();
}

uploadimages.ashx

<%@ WebHandler Language="C#" Class="uploadimages" %>

using System;
using System.Web;

public class uploadimages : IHttpHandler {

public void ProcessRequest (HttpContext context) {
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/userimages/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "text/plain";
context.Response.Write("Image Uploaded successfully!");
}
}

public bool IsReusable {
get {
return false;
}
}

}

1 Comment

  1. Very informative blog. Great.

Leave a Reply

Prabhakaran Jayaraman