Upload image using AJAX without handler c#
AJAX makes data transaction very fast in application without post back of a page. In this article i have uploaded image using AJAX without handler.
There are lots of solutions in Google regarding upload image using AJAX with handler but handler is not working on server sometimes so i have converted image to DataURL
and from this DataURL generated bitmap image and then we can save it in folder.
Introduction
In this article we can upload image to perticular folder in just few easy steps.
I have used AJAX POST method to upload image ,AJAX is a short form of Asynchronous JavaScript and XML. Ajax is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications Ajax makes data transaction much faster tahn conventional codebehind. We can upload image using handler in AJAX method but sometimes it generates error in our application, so i have created small article regarding upload image using AJAX without handler In this article image will transfer in to DataURL on onchange event of a file upload after DataURL generated it passes to code behind and generates bitmap and we can easily save this bitmao image in our folder with bitmap.save() method. All the steps is described in detail below.
Code snippet
here one page having name uploadImage.aspx
1) uploadImage.aspx<!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></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
.myButton
{
-moz-box-shadow: inset 0px 1px 0px 0px #ffffff;
-webkit-box-shadow: inset 0px 1px 0px 0px #ffffff;
box-shadow: inset 0px 1px 0px 0px #ffffff;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9));
background: -moz-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background: -webkit-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background: -o-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background: -ms-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%);
background: linear-gradient(to bottom, #f9f9f9 5%, #e9e9e9 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9',GradientType=0);
background-color: #f9f9f9;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
border: 1px solid #dcdcdc;
display: inline-block;
cursor: pointer;
color: #666666;
font-family: arial;
font-size: 15px;
font-weight: bold;
padding: 6px 24px;
text-decoration: none;
text-shadow: 0px 1px 0px #ffffff;
}
.myButton:hover
{
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #e9e9e9), color-stop(1, #f9f9f9));
background: -moz-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background: -webkit-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background: -o-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background: -ms-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%);
background: linear-gradient(to bottom, #e9e9e9 5%, #f9f9f9 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e9e9e9', endColorstr='#f9f9f9',GradientType=0);
background-color: #e9e9e9;
}
.myButton:active
{
position: relative;
top: 1px;
}
.style1
{
height: 45px;
width: 242px;
}
.style2
{
width: 242px;
}
.tbl
{
position: fixed;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -200px;
}
</style>
<script>
function PreviewImage(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function (e) {
hdnSource.value = e.target.result; //Generated DataURL
hdnFileName.value = input.value.split("\\")[2]; //uploaded file Name
document.getElementById("imgShowPreview").src = e.target.result; //Set Source for preview
}
filerdr.readAsDataURL(input.files[0]);
}
}
function UploadFile() {
$.ajax({
type: "POST",
url: "uploadImage.aspx/UploadFile", //pageName.aspx/MethodName
contentType: "application/json;charset=utf-8",
data: "{'dataURL':'" + hdnSource.value + "','fileName':'" + hdnFileName.value + "'}", // pass DataURL to code behind
dataType: "json",
success: function (data) {
alert(data.d); // Success function
},
error: function (result) {
alert(result.d); //Error function
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" id="hdnSource" value="" />
<input type="hidden" id="hdnFileName" value="" />
<div>
<table class="tbl">
<thead>
<tr>
<td class="style1">
File upload by : Nirav Prabtani
</td>
</tr>
</thead>
<tr>
<td class="style2">
<input type="file" name="filUpload" id="filUpload" onchange="PreviewImage(this)" />
</td>
</tr>
<tr>
<td class="style2">
<img id="imgShowPreview" height="250px" width="250px" />
</td>
</tr>
<tr>
<td class="style2">
<span onclick="UploadFile()" class="myButton">Save Image</span>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
when we select file than "PreviewImage(this)" function called and DataURL
generate from image and it will saved in hiddenfield.
When we click on "Save Image" button than "UploadFile()" function calls and it passes DataURL to code behind
2) uploadImage.aspx.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.IO;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace uploadImage
{
public partial class uploadImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string UploadFile(string dataURL, string fileName)
{
try {
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/image")))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/image"));
}
Bitmap varBmp = Base64StringToBitmap(dataURL);
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Dispose();
varBmp = null;
newBitmap.Save(System.Web.Hosting.HostingEnvironment.MapPath("~/image/" + Path.GetFileNameWithoutExtension(fileName) + ".Jpeg"));
return "File has been uploaded successfully..!!";
}
catch(Exception ex) {
return ex.Message.ToString();
}
}
public static Bitmap Base64StringToBitmap(string base64String)
{
Bitmap bmpReturn = null;
byte[] byteBuffer = Convert.FromBase64String(base64String.Split(',')[1].ToString());
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;
return bmpReturn;
}
}
}
When DataURL pass from javascript to codebehind than directory will create having name "image" and this DataURL will be convert in to bitmap using "Base64StringToBitmap" and this bitmap will be stored in image folder.
Conclusion
In this way it is very easy to save bitmap image in perticular folder. You can modify
this code acccording to your need. You can insert image DataURL or image path in
Database and retrieve it from database and you can bind it in gridview or repeater
as you want.
History
Initial level : 05 August 2014,
Second release will be soon with jQuery slider.Screen Shot