Preview & upload Image file using jquery with generic handler ashx without postback
Step 1 : UploadImage.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>uploading file using jquery with generic handler ashx</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#btnUpload').click(function () {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var test = new FormData();
for (var i = 0; i < files.length; i++) {
test.append(files[i].name, files[i]);
}
$.ajax({
url: "UploadHandler.ashx",
type: "POST",
contentType: false,
processData: false,
data: test,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
});
})
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function (e) {
$('#imgprvw').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
$('#imgprvw').show();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="file" id="FileUpload1" onchange="showimagepreview(this)" />
<input type="button" id="btnUpload" value="Upload Files" />
</div>
<img id="imgprvw" alt="uploaded image preview" width="200px" height="200px" style="display: none" />
</form>
</body>
</html>
Step 2 : UploadHandler.ashx
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : 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;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname = Path.Combine(context.Server.MapPath("~/uploads/"), fname);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
Comments
Post a Comment