How to upload image in asp.net using generic handler Ajax
Js Code:-
$("#btnAEsaverec").on('click', function () {
SaveRec();
})
function Saverecord() {
debugger
$("#tblmdltitle").text("Employee : Add");
debugger
var nmode = 0;
if ($("#hdnAEEmployee").val() == "") {
nmode = 1;
}
else {
nmode = 4;
}
var Empid = 0;
if ($("#hdnAEEmployee").val() != "") {
var Empid = $("#hdnAEEmployee").val();
}
var Fname = $("#txtAEFirstName").val();
var Lname = $("#txtAELasttName").val();
var DOB = $("#txtAEdob").val();
var Address = $("#txtAEaddress").val();
var Userrole = $("#ddlAEemprole").val();
var Mobile = $("#txtAEmobile").val();
var CurrentLocation = $("#txtAECurrentLocation").val();
var PinCode = $("#txtAEpincode").val();
var Filename = document.getElementById("inputfile").files[0];
$.ajax({
async: true,
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{'Fname': '" + $("#txtAEFirstName").val() + "', 'Lname': '" + $("#txtAELasttName").val() + "', 'DOB': '" + $("#txtAEdob").val() + "', 'Address': '" + Address + "', 'Userrole': '" + Userrole + "', 'Mobile': '" + Mobile + "', 'CurrentLocation': '" + CurrentLocation + "', 'PinCode': '" + PinCode + "','Filename': '" + Filename + "' }",
url: 'http://localhost:2228/smsmanagementsystem.asmx/EmployeeSave',
dataType: "json",
crossDomain: true,
success: function (data) {
debugger
var tt = JSON.stringify(data)
if (tt == { "d": "Save" } || data == { "d": "Update" }) {
swal({
title: "Employee",
text: "<p class='lead text-muted'>" + " Record " + data + " successfully" + " </p>",
type: "success",
showCancelButton: false,
html: true,
confirmButtonClass: 'btn-success',
confirmButtonText: 'OK'
}, function () {
swal.close();
ClearSubmit();
});
}
else {
swal({
title: "Employee",
text: "<p class='lead text-muted'>" + data + " </p>",
type: "error",
showCancelButton: false,
html: true,
confirmButtonClass: 'btn-success',
confirmButtonText: 'OK'
});
}
},
complete: function () {
$("#contributionSpinner").hide();
$("#btnsaveEmployee").removeAttr("disabled");
},
error: function (jqXHR, exception) {
$("#contributionSpinner").hide();
$("#btnsaveEmployee").removeAttr("disabled");
swal("Employee", getErrorMessage(jqXHR, exception), "error");
},
});
}
function SaveRec() {
var fileUpload = $("#inputfile").get(0);
var CatagoeryName = $("#ddlAEemprole option:selected").text();
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
data.append("ThumbFolderName", "Thumb");
data.append("CatagoeryName", CatagoeryName);
data.append("x", 45);
data.append("y", 35);
data.append("h", "55");
data.append("w", 77);
data.append("scalew", "55");
data.append("scaleh", 77);
var options = {};
options.url = "/Handler1.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (dt) {
debugger;
var Data = $.parseJSON(dt);
if (Data[0].Err_msg == "Success" && Data != null) {
if (Data.length > 0) {
$("#hdnpath1").val(Data[0].Path1);
$("#hdnpath2").val(Data[0].Path2);
alert("File Upload Success !!")
//$("#hdnpatherror").val(Data[0].Err_msg);
Saverecord();
}
} else {
alert('file upload failed');
}
};
options.error = function (Err_msg) { alert(Err_msg.statusText); };
$.ajax(options);
}
Hndeler Code File Save Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace schoolManagementSystem
{
/// <summary>
/// Summary description for Handler1
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
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("~/FileUpload/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("Done");
}
catch (Exception)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Failed");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Record Save Code:-
[WebMethod]
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using static Dapper.SqlMapper;
namespace schoolManagementSystem
{
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string Err_msg = "";
//string subdirectory = "";
string A = "Meal";
string B = "Thumb";
var path = "";
string Thumb_path = "";
try
{
DataTable dt = new DataTable();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
var CatagoeryName = context.Request.Form["CatagoeryName"];
var ThumbFolderName = context.Request.Form["ThumbFolderName"];
string LocalPath = ConfigurationManager.AppSettings["path"];
if (A == "Meal")
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string Meal = "Meal";
path = Path.Combine(CatagoeryName, Meal);
string fname = Path.Combine(LocalPath, path);
if (!(Directory.Exists(fname)))
{
Directory.CreateDirectory(fname);
}
var path1 = Path.Combine(fname, file.FileName);
file.SaveAs(path1);
}
}
if (B == "Thumb")
{
int x = int.Parse(context.Request["x"]);
int y = int.Parse(context.Request["y"]);
int h = int.Parse(context.Request["h"]);
int w = int.Parse(context.Request["w"]);
int scalew = int.Parse(context.Request["scalew"]);
int scaleh = int.Parse(context.Request["scaleh"]);
using (Image img = CustomCrop(w, h, x, y, scalew, scaleh, files))
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
Thumb_path = "Thumb";
Thumb_path = Path.Combine(CatagoeryName, Thumb_path);
string fname = Path.Combine(LocalPath, path);
if (!(Directory.Exists(fname)))
{
Directory.CreateDirectory(fname);
}
var path1 = Path.Combine(fname, file.FileName);
file.SaveAs(path1);
}
}
dt.Columns.Add("Path1", typeof(System.String));
dt.Columns.Add("Path2", typeof(System.String));
dt.Columns.Add("Err_msg", typeof(System.String));
DataRow row = dt.NewRow();
row["img"] = "path";
row["thumb"] = "hello";
row["Err_msg"] = "Success";
dt.Rows.Add(row);
}
string strResponse = JsonConvert.SerializeObject(dt);
context.Response.ContentType = "text / plain";
context.Response.Write(strResponse);
}
catch (Exception ex)
{
Err_msg = JsonConvert.SerializeObject(ex.ToString());
context.Response.ContentType = "text/plain";
context.Response.Write(Err_msg);
}
}
public bool IsReusable
{
get
{
return false;
}
}
public static Image CustomCrop(int width, int height, int x, int y, int scalwidth, int scalheight, HttpFileCollection files)
{
try
{
HttpPostedFile file = null;
for (int i = 0; i < files.Count; i++)
{
file = files[i];
}
Image image = Image.FromFile(file.FileName);
Bitmap bmp = new Bitmap(scalwidth, scalheight, PixelFormat.Format24bppRgb);
bmp.SetResolution(80, 60);
Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.DrawImage(image, new Rectangle(0, 0, scalwidth, scalheight), x, y, width, height, GraphicsUnit.Pixel);
return bmp;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
return null;
}
}
}
}
No comments:
Post a Comment