本文介绍了如何在控制器上上传表单提交的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using FirstLevel.Models.User;
using FirstLevel.ServiceReference2;
using Valentica.Libraries;
using System.Web.Security;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml;
using System.Text;
using System.Collections;
using System.ServiceModel;
namespace FirstLevel.Controllers
{
public class UserController : Controller
{
//
// GET: /User/
Service1Client sc = new Service1Client();
CompositeUserAdd cu = new CompositeUserAdd();
DBDataContext db = new DBDataContext();
UserBL BL = new UserBL();
public ActionResult Index(string Keyword, int? pageid, int? pagesize)
{
try
{
sc.Open();
var list = sc.GetAllUserData();
//for pagination
Session["Keyword"] = (String.IsNullOrEmpty(pageid.ToString())) ? Keyword : Session["Keyword"];
Keyword = (string)Session["Keyword"] != "" ? (string)Session["Keyword"] : Keyword;
if (Keyword != null && Keyword != "")
{
list = list.Where(c => c.Firstname.Contains(Keyword)).ToArray();
}
//Pagination Code
if (pageid != -1)
{
int page = (String.IsNullOrEmpty(pageid.ToString())) ? 1 : Int32.Parse(pageid.ToString());
int pagesz = (String.IsNullOrEmpty(pagesize.ToString())) ? 5 : Int32.Parse(pagesize.ToString());
int TotRecord = list.Count();
Pagination pagination = new Pagination(true);
pagination.BaseUrl = "/User/Index?pageid=";
pagination.TotalRows = TotRecord;
pagination.CurPage = page;
pagination.PerPage = pagesz;
pagination.PrevLink = "Prev";
pagination.NextLink = "Next";
string pageLinks = pagination.GetPageLinks();
int start = (page - 1) * pagination.PerPage;
int offset = pagination.PerPage;
ViewData["offset"] = (start + pagesz);
list = list.Skip(start).Take(offset).ToArray();
ViewData["totalUsers"] = TotRecord;
ViewData["users"] = list;
ViewData["pageLinks"] = pageLinks;
ViewData["offset"] = (start + pagesz);
}
sc.Close();
return View(list);
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
[HttpGet]
public ActionResult Create()
{
try
{
sc.Open();
//division Dropdown
List<getdivisionname> list = new List<getdivisionname>();
List<SelectListItem> divisionname = new List<SelectListItem>();
divisionname.Add(new SelectListItem { Text = "Select Division name", Value = "0", Selected = true });
list = sc.GetDivisionName().ToList();
foreach (var x in list)
{
divisionname.Add(new SelectListItem { Text = x.Divisionname, Value = x.Divisionid.ToString() });
}
ViewData["division"] = null;
ViewData["division"] = divisionname;
//Subdivision Dropdown
List<SelectListItem> subdivisionname = new List<SelectListItem>();
subdivisionname.Add(new SelectListItem { Text = "Select Sub Division", Value = "0" });
ViewData["subdivision"] = null;
ViewData["subdivision"] = subdivisionname;
//org Dropdown
List<SelectListItem> orgname = new List<SelectListItem>();
orgname.Add(new SelectListItem { Text = "Select Organization", Value = "0", Selected = true });
ViewData["org"] = null;
ViewData["org"] = orgname;
//district Dropdown
List<SelectListItem> district = new List<SelectListItem>();
List<getdistrictname> distlist = new List<getdistrictname>();
district.Add(new SelectListItem { Text = "Select District", Value = "0", Selected = true });
distlist = sc.GetDistrictName().ToList();
foreach (var dx in distlist)
{
district.Add(new SelectListItem { Text = dx.Distname, Value = dx.Distid.ToString() });
}
ViewData["Distbind"] = null;
ViewData["Distbind"] = district;
//taluka Dropdown
List<SelectListItem> taluka = new List<SelectListItem>();
taluka.Add(new SelectListItem { Text = "Select taluka", Value = "0" });
ViewData["Talubind"] = null;
ViewData["Talubind"] = taluka;
//rolename Dropdown
List<SelectListItem> rolename = new List<SelectListItem>();
rolename.Add(new SelectListItem() { Text = "---Select Role---", Value = "0", Selected = true });
var listR = sc.GetRoleName();
foreach (var x in listR)
{
rolename.Add(new SelectListItem() { Text = x.Rolname, Value = x.Rolid.ToString() });
}
ViewData["Rolebind"] = null;
ViewData["Rolebind"] = rolename;
sc.Close();
ViewData["List"] = null;
ViewData["List"] = BL.List;
return View();
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
public string GetDisName(int Id)
{
try
{
string ans = "";
List<SelectListItem> Taluname = new List<SelectListItem>();
int Id1 = Id;
if (sc.State == CommunicationState.Closed)
{
sc.Open();
}
var listT = sc.Gettalukaname1(Id1);
string disname = sc.getdistirctname(Id);
Session["dname"] = disname;
sc.Close();
if (listT.Count() > 0)
{
ans += "<select id=\"Taluka1\" class=\"insertInput\">";
ans += "<option value=\"0\">--All--</option>";
foreach (var x in listT)
{
ans += "<option value=\"" + x.Taluid + "\" >" + x.Taluname + "</option>";
Session["tal"] = x.Taluname;
}
}
return ans;
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
public static Image ScaleImage(Image image, int maxHeight)
{
try
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
[HttpPost]
public ActionResult Create(UserBL UL, FormCollection Form)
{
try
{
string Upload = Form["Upload"] != null ? Form["Upload"].ToString() : "";
string Createbtn = Form["Create"] != null ? Form["Create"].ToString() : "";
HttpPostedFileBase file = UL.UploadFile;
if (Upload == "Upload")
{
if (file.ContentLength > 0 && file.ContentLength < 1 * 1024 * 1024)
{
string fileExtension = file.ContentType;
if (fileExtension == "image/jpeg" || fileExtension == "image/jpg" || fileExtension == "image/png" || fileExtension == "image/gif")
{
Bitmap bmpPostedImage = new System.Drawing.Bitmap(file.InputStream);
Image objimage = ScaleImage(bmpPostedImage, 100);
string filePath = Path.Combine(HttpContext.Server.MapPath("../UploadedImages"), Path.GetFileName(file.FileName));
objimage.Save(filePath, ImageFormat.Gif);
ViewData["FileName"] = file.FileName;
// UL.filename = null;
//ViewData["List"] = UL.List;
byte[] imageData = System.IO.File.ReadAllBytes(filePath);
UL.Filee = imageData;
ViewData["List"] = BL.List;
List<SelectListItem> distname = new List<SelectListItem>();
distname.Add(new SelectListItem() { Text = "--Select District--", Value = "0", Selected = true });
List<SelectListItem> Taluname = new List<SelectListItem>();
Taluname.Add(new SelectListItem() { Text = "--Select Taluka--", Value = "0", Selected = true });
List<SelectListItem> rolename = new List<SelectListItem>();
rolename.Add(new SelectListItem() { Text = "---Select Role---", Value = "0", Selected = true });
sc.Open();
var list = sc.GetDistrictName();
foreach (var x in list)
{
distname.Add(new SelectListItem() { Text = x.Distname, Value = x.Distname.ToString() });
}
List<SelectListItem> district = new List<SelectListItem>();
List<getdistrictname> distlist = new List<getdistrictname>();
district.Add(new SelectListItem { Text = "Select District", Value = "0", Selected = true });
distlist = sc.GetDistrictName().ToList();
foreach (var dx in distlist)
{
district.Add(new SelectListItem { Text = dx.Distname, Value = dx.Distid.ToString() });
}
ViewData["Distbind"] = null;
ViewData["Distbind"] = district;
//var listT = sc.GetTalukaName();
//foreach (var x in listT)
//{
// Taluname.Add(new SelectListItem() { Text = x.Taluname, Value = x.Taluname.ToString() });
//}
var listR = sc.GetRoleName();
foreach (var x in listR)
{
rolename.Add(new SelectListItem() { Text = x.Rolname, Value = x.Rolid.ToString() });
}
ViewData["Talubind"] = null;
ViewData["Talubind"] = Taluname;
ViewData["Distbind"] = null;
ViewData["Distbind"] = distname;
ViewData["Rolebind"] = null;
ViewData["Rolebind"] = rolename;
sc.Close();
ViewData["List"] = null;
ViewData["List"] = BL.List;
return View("Create",UL);
}
else
{
ViewData["Errormsgtype"] = "";
ViewData["Errormsgtype"] = "Please Only Jpeg, GIf or png Image Upload.";
ViewData["List"] = BL.List;
return View(UL);
}
}
}
else if (Createbtn == "Create")
{
if (UL.filename == null)
{
UL.filename = "default.gif";
var uploads = Request.Files["img12345"];
byte[] imageData = System.IO.File.ReadAllBytes(Server.MapPath("~/UploadedImages/") + UL.filename);
UL.Filee = imageData;
}
else
{
var uploads = Request.Files["img12345"];
byte[] imageData = System.IO.File.ReadAllBytes(Server.MapPath("~/UploadedImages/") + UL.filename);
UL.Filee = imageData;
}
string l = UL.FirstName.Replace(" ", "").Trim();
string l1 = l.Substring(0, 1).ToUpper();
string l2 = l.Substring(1);
string l3 = l1 + l2;
string l4 = UL.LastName.Replace(" ", "").Trim();
string l5 = l4.Substring(0, 1).ToUpper();
string l6 = l4.Substring(1);
string l7 = l5 + l6;
string l8 = UL.UserName.Replace(" ", "").Trim();
string l9 = l8.Substring(0, 1).ToUpper();
string l10 = l8.Substring(1);
string l11 = l9 + l10;
cu.Firstname = l3;//change on 06-08-13 UL.FirstName;
cu.Lastname = l7;//change on 06-08-13 UL.LastName;
cu.Loginname = UL.UserName;//change on 06-08-13 UL.UserName;
cu.Image = UL.Filee;
cu.Address = UL.Address;
cu.DistrictId = UL.DistrictID;// UL.District;
cu.TalukhaId = Convert.ToInt16(Session["tal"]);// UL.Taluka;
cu.Pincode = UL.Pincode;
cu.Mobileno = UL.MobileNo;
cu.Contactno = UL.PhoneNo;
cu.Mobileno = UL.MobileNo;
cu.Role = UL.RoleID;
cu.Email = UL.Email;
cu.Sequrityquestion = UL.SecurityQuestion;
cu.Answer = UL.Answer;
cu.Createby = Convert.ToInt32(Session["UserID"].ToString());
cu.Updateby = Convert.ToInt32(Session["UserID"].ToString());
cu.Password = UL.Password;
if (Session["offrid"] != null)
{
cu.officierid = Convert.ToInt32(Session["offrid"].ToString());
Session["offrid"] = null;
}
else
{
cu.officierid = 0;
}
cu.Active = UL.Active == true ? cu.Active = 'Y' : cu.Active = 'N';
// cu.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(UL.Password, "MD5");//UL.Password;
cu.Confirmpassword = UL.ConfirmPassword;
sc.Open();
ViewData["List"] = null;
ViewData["List"] = UL.List;
sc.AddUserDataContract(cu);
sc.Close();
//if (if == 1)
//{
ViewData["Success"] = "Insert Successfuly";
//}
Session["dname"] = null;
Session["tal"] = null;
}
}
catch
{
}
return RedirectToAction("Index");
}
[HttpPost]
public string SomeActionMethod(string UseName)
{
try
{
string IsExist = "No";
var User = from c in db.User_masters where c.User_name == UseName select c.User_name;
if (User.Count() > 0)
{
IsExist = "Yes";
}
return IsExist;
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
[HttpPost]
public string GetRoles(string Name)
{
try
{
string ReturnStr = "";
var List = from c in db.User_roles
where c.IsActive == 'Y'
&& c.Userrole_name.Contains(Name)
select new { c.Userrole_name, c.Userrole_id, c.IsActive };
if (List.Count() > 0)
{
ReturnStr = "<table style="\"width:600px\"" id="\"Simple\""><tr></tr><tr><td colspan="\"4\""><input type=\"text\" id=\"Filtertext\" /><input type=\"button\" id=\"Filterbutton\" value=Filter onclick=\"Filter();\"/></td></tr><tr><td colspan="\"4\""><div id="\"ScrollDiv\""><table id="\"Popup\"" width="\"100%\""><tr><th>Role Name</th><th>Active</th><th>Select</th><tr>";
//ReturnStr = "<table style="\"width:400px\"" id="\"Popup\""><tr></tr></table></tr></tr></table></div></td></tr><tr><th>Name</th><th>Address</th><th>Department</th><th>Dist. Head Name</th><th>Select</th><tr>";
foreach (var Var in List)
{
ReturnStr += "<tr><td>" + Var.Userrole_name + "</td><td>" + Var.IsActive + "</td><td><a href="\"javascript:void(0)\"" öndblclick="\"SetRole('"" var.userrole_name="" var.userrole_id="">Select</a></td></tr>";
}
ReturnStr += "</tr></tr></table>";
}
else
{
ReturnStr = "<table style="\"width:600px\"" id="\"Simple\""><tr></tr><tr><td colspan="\"4\"" width="\"400px\""><input type=\"text\" id=\"Filtertext\" /><input type=\"button\" id=\"Filterbutton\" value=Filter onclick=\"Filter()\"/></td></tr>";
ReturnStr += "<tr><td><table id="\"Simple\"" width="\"100%\""><tr><td style="\"border:0px;\"" width="\"50%\"">No Role Found !!</td><td style="\"border:0px;\"" width="\"50%\"" align="\"right\""> <a href="\"../Role/Create\"">Add New Role </a></td></tr></table></td></tr></table>";
}
return ReturnStr;
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
public string Getofficierlist(int id)
{
try
{
if (sc.State == CommunicationState.Closed)
{
sc.Open();
}
List<servicereference2.getofficiername> list = new List<getofficiername>();
list = sc.GetofficierList(id).ToList();
sc.Close();
string ans = "";
if (list.Count() > 0)
{
ans += "<Select id=\"offid\" onchange=\"getoffid();\" class=\"insertInput\">";
ans += "<option value=\"0\" >--ALL--</option>";
foreach (var subdivname in list)
{
ans += "<option value=\"" + subdivname.offid + "\">" + subdivname.offName + "</option>";
}
}
return ans;
}
catch (Exception ex)
{
string ans = "error";
return ans;
}
}
public void Getoffcr(int Id)
{
Session["offrid"] = Id;
return;
}
public ActionResult Edit(int Id)
{
try
{
CompositeUserAdd ct = new CompositeUserAdd();
ct.UserId = Id;
sc.Open();
ct = sc.CompositeUserAddEdit(ct);
UserBL ul = new UserBL();
ul.FirstName = ct.Firstname;
ul.LastName = ct.Lastname;
ul.UserName = ct.Loginname;
ul.Email = ct.Email;
ul.Address = ct.Address;
ul.RoleID = ct.Role;
ul.RoleName = ct.RoleName;
ul.District = ct.District;
ul.Taluka = ct.Taluka;
ul.DistrictID = ct.DistrictId;
ul.TalukaID = ct.TalukhaId;
ul.Pincode = ct.Pincode;
ul.PhoneNo = ct.Contactno;
ul.MobileNo = ct.Mobileno;
ul.SecurityQuestion = ct.Sequrityquestion;
ul.Password = "000000";
ul.ConfirmPassword = "000000";
ul.Answer = ct.Answer;
ul.ID = ct.UserId;
if (ct.Active == 'Y')
{
ul.Active = true;
}
else
{
ul.Active = false;
}
List<SelectListItem> distname = new List<SelectListItem>();
List<SelectListItem> Taluname = new List<SelectListItem>();
List<SelectListItem> rolename = new List<SelectListItem>();
List<SelectListItem> securityq = new List<SelectListItem>();
var list = sc.GetDistrictName();
int flag2 = 0;
foreach (var x in list)
{
if (flag2 == 0 && ul.District == x.Distname)
{
distname.Add(new SelectListItem() { Text = x.Distname, Value = x.Distid.ToString(), Selected = true });
flag2 = 1;
}
if (ul.District != x.Distname)
{
distname.Add(new SelectListItem() { Text = x.Distname, Value = x.Distid.ToString() });
}
}
var listT = sc.GetTalukaName(ct.District);
int flag1 = 0;
foreach (var x in listT)
{
if (flag1 == 0 && ul.Taluka == x.Taluname)
{
Taluname.Add(new SelectListItem() { Text = x.Taluname, Value = x.Taluid.ToString(), Selected = true });
flag1 = 1;
}
if (ul.RoleName != x.Taluname)
{
Taluname.Add(new SelectListItem() { Text = x.Taluname, Value = x.Taluid.ToString() });
}
}
var listR = sc.GetRoleName();
int flag = 0;
foreach (var x in listR)
{
if (flag == 0 && ul.RoleName == x.Rolname)
{
rolename.Add(new SelectListItem() { Text = x.Rolname, Value = x.Rolid.ToString(), Selected = true });
flag = 1;
ul.RoleID = x.Rolid;
}
if (ul.RoleName != x.Rolname)
{
rolename.Add(new SelectListItem() { Text = x.Rolname, Value = x.Rolid.ToString() });
}
}
var listS = BL.List;
int flags = 0;
foreach (var x in listS)
{
if (flags == 0 && ul.SecurityQuestion.ToString() == x.Value)
{
securityq.Add(new SelectListItem() { Text = x.Text, Value = x.Value, Selected = true });
}
if (ul.SecurityQuestion.ToString() != x.Value)
{
securityq.Add(new SelectListItem() { Text = x.Text, Value = x.Value });
}
}
ViewData["Talubind"] = null;
ViewData["Talubind"] = Taluname;
ViewData["Distbind"] = null;
ViewData["Distbind"] = distname;
ViewData["Rolebind"] = null;
ViewData["Rolebind"] = rolename;
sc.Close();
ViewData["List"] = null;
ViewData["List"] = securityq;
return View(ul);
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
[HttpPost]
public ActionResult Edit(int Id, UserBL UL, FormCollection Form)
{
try
{
string Upload = Form["Upload"] != null ? Form["Upload"].ToString() : "";
string Createbtn = Form["Create"] != null ? Form["Create"].ToString() : "";
HttpPostedFileBase file = UL.UploadFile;
if (Upload == "Upload")
{
if (file.ContentLength > 0 && file.ContentLength < 1 * 1024 * 1024)
{
string fileExtension = file.ContentType;
if (fileExtension == "image/jpeg" || fileExtension == "image/jpg" || fileExtension == "image/png" || fileExtension == "image/gif")
{
Bitmap bmpPostedImage = new System.Drawing.Bitmap(file.InputStream);
Image objimage = ScaleImage(bmpPostedImage, 100);
string filePath = Path.Combine(HttpContext.Server.MapPath("../UploadedImages"), Path.GetFileName(file.FileName));
objimage.Save(filePath, ImageFormat.Gif);
ViewData["FileName"] = file.FileName;
// UL.filename = null;
//ViewData["List"] = UL.List;
byte[] imageData = System.IO.File.ReadAllBytes(filePath);
UL.Filee = imageData;
ViewData["List"] = BL.List;
return View(UL);
}
else
{
ViewData["Errormsgtype"] = "";
ViewData["Errormsgtype"] = "Please Only Jpeg, GIf or png Image Upload.";
ViewData["List"] = BL.List;
return View(UL);
}
}
}
else if (Createbtn == "Save")
{
if (UL.filename == null)
{
UL.filename = "default.gif";
}
else
{
byte[] imageData = System.IO.File.ReadAllBytes(Server.MapPath("~/UploadedImages/") + UL.filename);
UL.Filee = imageData;
}
cu.UserId = Id;
cu.Firstname = UL.FirstName;
cu.Lastname = UL.LastName;
cu.Loginname = UL.UserName;
cu.Address = UL.Address;
cu.DistrictId = UL.DistrictID;
cu.TalukhaId = UL.TalukaID;
cu.Pincode = UL.Pincode;
cu.Mobileno = UL.MobileNo;
cu.Contactno = UL.PhoneNo;
cu.Mobileno = UL.MobileNo;
cu.Role = UL.RoleID;
cu.Email = UL.Email;
cu.Sequrityquestion = UL.SecurityQuestion;
cu.Answer = UL.Answer;
if(UL.Password != null && UL.Password !="000000")
{
cu.Password = UL.Password;
}
if (UL.ConfirmPassword != null && UL.ConfirmPassword != "000000")
{
cu.Confirmpassword = UL.ConfirmPassword;
}
cu.Active = UL.Active == true ? cu.Active = 'Y' : cu.Active = 'N';
// cu.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(UL.Password, "MD5");//UL.Password;
cu.Confirmpassword = UL.ConfirmPassword;
sc.Open();
ViewData["List"] = null;
ViewData["List"] = UL.List;
sc.CompositeUserAddUpdate(cu);
sc.Close();
//if (if == 1)
//{
ViewData["Success"] = "Insert Successfuly";
//}
}
}
catch
{
return View(UL);
}
return RedirectToAction("Index");
}
public string Delete(int Id)
{
try
{
sc.Open();
int ct = sc.CompositeUserDelete(Id);
sc.Close();
if (ct == 1)
{
return "success";
}
else
{
return "Failed";
}
}
catch (Exception ex)
{
throw new ApplicationException("some error occured", ex);
}
}
}
}
推荐答案
这篇关于如何在控制器上上传表单提交的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!