Thursday, April 18

How to Upload and Save Image Without any Postback by User in Asp.net

Introduction:-
                  Here I have explained how to store and display image instantly after choose by user in asp.net using jQuery.
Description:-
                 In this article I have explained how to avoid upload button functionality after choosing a image in asp.net. Some users usually don't likes to view image after clicked on upload button or any button control,They always prefers to view image instantly after selecting a specific image from dialog box.
               It make sense that it will possible only if we will use ajax or some client side functions.so here I am using javascript functions with taking one Image control and File upload button to open a dialog to choose a image from it.In my other post I have explained
How to Update previous Image URL During Update Mode , and  FileUpload Content Refreshed During pageloadif it is used in a user control .
 
 To get the result follow the below steps. where I  have explained each content with source code.


Here is my file Upload control
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<input type="file" id="img_Upload" name="img_Upload" onchange="ReadImage(this);" />
<asp:Image ID="ImgUser" Height="171px" Width="153px" ImageUrl="~/UserImage/default_user.jpg" runat="server"></asp:Image>
When you will choose the image it will directly reflect to Image control ,for this i have written one javascript function as "ReadImage" .Here is the function
<script type="text/javascript">
    function CheckFileType() {
        var filenm = $("#img_Upload").val();
        if (filenm.lastIndexOf('.') && filenm.length > 5)
            filenm = filenm.substring(filenm.lastIndexOf('.'), filenm.length).toLowerCase().trim();
        if (filenm != ".jpeg" && filenm != ".jpg" && filenm != ".gif" && filenm != ".png") {
            alert('Invalid Image Format');
            return false
        }
        return true;
    }
    function ReadImage(input) {
        if (CheckFileType()) {
            var file = input.files[0];
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#<%=ImgUser.ClientID %>').attr('src', e.target.result);
                $('#ImgUser').attr('src', e.target.result);
                $('#<%=hdnImg.ClientID %>').val(e.target.result);
                LoadData(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    }
</script>
Now To Auto Save this Image I have written one more Javacript Function where i have called a asp page as PostFile.aspx.
Here is my Javascript function
function LoadData(img) {
 $.post("PostFile.aspx", { img: img }, function (data, status) {
alert('done');
});
 }
And in Pageload event ofPostFile.aspx Write the following code
Here is my code behind
Using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
 
namespace EDAU
{
public partial class PostFile : System.Web.UI.Page
{
string imagename = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
SaveImage();
}
 
private void SaveImage()
{
try
{
byte[] decodedData = base64Decode(Request["img"]);
imagename = Guid.NewGuid().ToString();
System.IO.File.WriteAllBytes(Server.MapPath("~/Temp/" + imagename + ".jpeg"), decodedData);
Session["UserImage"] = imagename + ".jpeg";
//I have taken one Temp folder to store image temporary
Bitmap source = (Bitmap)Bitmap.FromFile(Server.MapPath("~/Temp/" + imagename + ".jpeg"));
Bitmap bmpProfileImage = new System.Drawing.Bitmap(171, 153);
Bitmap ThumbNail = new System.Drawing.Bitmap(30, 30);
Graphics g1 = Graphics.FromImage(bmpProfileImage);
g1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g1.FillRectangle(System.Drawing.Brushes.White, 0, 0, 100, 100);
g1.DrawImage(source, 0, 0, 171, 153);
Graphics g = Graphics.FromImage(ThumbNail);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(System.Drawing.Brushes.White, 0, 0, 100, 100);
g.DrawImage(source, 0, 0, 30, 30);
 
string saveImagePath = Server.MapPath("~/UserImage/Thumbnail/") + imagename + ".jpeg";
ThumbNail.Save(saveImagePath, ImageFormat.Jpeg);
saveImagePath = Server.MapPath("~/UserImage/") + imagename + ".jpeg";
bmpProfileImage.Save(saveImagePath,ImageFormat.Jpeg);
g1.Dispose(); g.Dispose(); bmpProfileImage.Dispose(); ThumbNail.Dispose();
File.Delete(Server.MapPath("~/Temp/" + imagename + ".jpeg"));
}
catch (Exception ex)
{ }
}
public static byte[] base64Decode(string data)
{
char[] ch = { ':', ',' };
string [] d = data.Split(ch);
return Convert.FromBase64String(d[2]);
}
}
}
In this article one more thing I want to say that, there is javascript function CheckFileType(),after looking that function there is no doubt,why I am using that function.This will validate the proper file extensions of that image.
Keep coding...  
Thanks Shibashish Mohanty
 
 

1 comment:

  1. Is there any limit on the uploaded image. I tried with 6 MB Photos. Then this methdd didn't saved the file in temporary location

    ReplyDelete

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty