AJAX简单demo

前端之家收集整理的这篇文章主要介绍了AJAX简单demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

A。前台


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<l<link href="handle/pop.css" rel="stylesheet" type="text/css" />
<link href="handle/base.css" rel="stylesheet" type="text/css" />
<link href="handle/user.css" rel="stylesheet" type="text/css" />
<script src="http://api.map.baidu.com/api?v=2.0&ak=DRoubqPLrWO98RnQrOHZ02NI" type="text/javascript"></script>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="My97DatePicker/WdatePicker.js" type="text/javascript"></script>

<script src="js/city.min.js" type="text/javascript"></script>
<script src="js/jquery.cityselect.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="js/uploadify/uploadify.css" />
<script type="text/javascript" src="js/uploadify/jquery.uploadify.min.js"></script>


<script type="text/javascript">

// 提示
function showTip(id,msg) {
$("#" + id).show().css({ "color": "red" });
$("#" + id).html(msg);
$("#" + id).show();
setTimeout(function () {
$("#" + id).hide();
},3000);
}


$(document).ready(function () {

// 招聘会服务模式选择
$("#meetType a").bind("click",function () {

$("#meetType a").removeClass("sele");
$(this).addClass("sele");
var select = $("#meetType a[class='sele']").text();
alert(select);
});

$("#wl li").bind("click",function () {
$("#wl li").removeClass("sele");

$(this).addClass("sele");
var s = $("#wl li[class='sele']").text();
alert(s);
});

//招聘会个人及单位门票是否收费的选择
$("#ticketSetting a").bind("click",function () {
var parentName = $(this).parent().attr("name");
if ($(this).text() == "收费") {

$("div[name='" + parentName + "_div']").show();

if (parentName == "pOn" || parentName == "pOff") { // 设置如果招聘会收费则不设置人工审核
$("#auditSetting div[name='pAudit']").find("a").eq(1).hide();
$("#auditSetting div[name='pAudit']").find("a").eq(0).trigger("click");
}
else {
$("#auditSetting div[name='cAudit']").find("a").eq(1).hide();
$("#auditSetting div[name='cAudit']").find("a").eq(0).trigger("click");
}
}
else {
$("div[name='" + parentName + "_div']").hide();
$("#ticketSetting div[name='" + parentName + "_div'] input[type='text']").val("");

if (parentName == "pOn" || parentName == "pOff") {
$("#auditSetting div[name='pAudit']").find("a").eq(1).show();
//$("#auditSetting div[name='pAudit']").find("a").eq(0).trigger("click");
}
else {
$("#auditSetting div[name='cAudit']").find("a").eq(1).show();
//$("#auditSetting div[name='cAudit']").find("a").eq(0).trigger("click");
}
}
$("#ticketSetting span[name='" + parentName + "_select']").text($(this).text());
});


// $('#petsimage').find('a').eq('1').click(function () {
// alert($(this).html());
// });
$('#petsimage').find('a').eq('1').trigger('click');


//地图
// 招聘会地址选择
$("#city_select").citySelect({
provId: "prov",
cityId: "city",
distId: "dist",
prov: "湖北",
city: "武汉",
dist: "武昌区",
nodata: "none"
});

var fnMeetAdd = function () {
if (_meetData.isGettingPoint) {
setTimeout(fnMeetAdd,200);
return;
}
meetAdd();
}

var _meetData = {
lng: 0,
lat: 0,
isGettingPoint: false,
setPosition: function (lng,lat) {
_meetData.lng = lng;
_meetData.lat = lat;
$('#spanPositionTip').css("display","none");
console.log('lng:' + _meetData.lng + ' lat:' + _meetData.lat);
}
};
window.MeetData = _meetData;

var oldPlace = '';
$("#txtPlace").bind("blur",function () {
var place = this.value.Trim();
if (oldPlace == place) return;
oldPlace = place;
if (place == '') return;
_meetData.isGettingPoint = true;
var myGeo = new BMap.Geocoder();
myGeo.getPoint(place,function (point) {
if (point) {
$('#spanPositionTip').css("display","none");
_meetData.lng = point.lng;
_meetData.lat = point.lat;
} else {
$('#spanPositionTip').css("display","");
_meetData.lng = 0;
_meetData.lat = 0;
}
_meetData.isGettingPoint = false;
},$('#city').val());
});

var fnShowMap = function () {
if (_meetData.isGettingPoint) {
setTimeout(fnShowMap,200);
return;
}
var title = "设置地图坐标";
var url = 'Map.aspx';
if (_meetData.lng > 0 && _meetData.lat > 0)
url = "Map.aspx?lng=" + _meetData.lng + "&lat=" + _meetData.lat;
else {
var city = $('#city').val();
if (city != '')
url = "Map.aspx?city=" + encodeURIComponent(city);
}
$.dialog({
title: title,
max: false,
min: false,
id: 'userSelect',
height: "600px",
width: "800px",
content: "url:" + url,
lock: true,
init: function () {
}
});
};

$("#hlShowMap").bind("click",fnShowMap);

//修改
$("#bt_up").bind("click",function () {
var id = $("#txtid").val();
var names = $("#txt_name").val();
$.ajax({
type: "post",
dataType: "text",
url: "test.ashx",
cache: false,
data: { operate: "update",id: id,name: names },
success: function (text,textStatus) {
if (text != null) {

var data = eval("(" + text + ")");
if (data.flag == 'true') {

$("#tip").text(data.msg);
}
else {
$("#tip").text(data.msg);

}

// if (text == "ok") {
// $("#tip").text("格式正确......");
// }
// else {
// $("#tip").text("格式错误......");
//
// }
}


}
});

});

$("#getimg").click(function () {

loadPicList();
});


$("#sendimg").click(function () {


uploadImg("filePersonHead","personHead","user.png");
});

//查询文件夹下的头像显示
function loadPicList() {
var uid = $("#txtid").val();
$.ajax({
type: "get",
dataType: "json",
//async: false,
data: { operate: "getPicList","userid": uid },
beforeSend: function () {
},
success: function (text) {
$(".albums li").remove();
if (text != null) {

$.each(text,function (i,item) {
var htmlstr = "<li style='background: url(" + item.url + "); width: 150px; height: 50px;'></li>";
$(".albums").append(htmlstr);
});
}
else {

var htmlstr = "<li style='background: url(../../images/user-photo1.jpg); width: 50px; height: 30px;'></li>";
$(".albums").append(htmlstr);
}
},
complete: function (XMLHttpRequest,textStatus) {
},
error: function (XMLHttpRequest,textStatus,errorThrown) {
//alert(XMLHttpRequest.responseText);
}
});
}



// 图片上传
function uploadImg(fileId,imgPreviewId,hidId) {
$("#" + fileId).uploadify({
auto: true,
swf: 'js/uploadify/uploadify.swf',
formData: { 'operate': 'uploadImage','oldImg': $("#" + hidId).val() },
uploader: 'test.ashx',
fileTypeDesc: 'Image Files',
fileTypeExts: '*.gif; *.jpg; *.png;',
buttonText: '选择图片...',
fileSizeLimit: '2Mb',
queueSizeLimit: 1,
// onUploadStart: function (file) {
// //alert($("#" + hidId).val());
// $("#" + fileId).uploadify("settings","oldImg",$("#" + hidId).val());
// alert($("#" + fileId).uploadify('settings','oldImg'));
// },
onUploadSuccess: function (file,data,response) {
if (data == null || data == "")
return;
var imgInfo = eval("(" + data + ")");
//var imgInfo = data;
var maxSize = 120;
var width = imgInfo.imgWidth;
var height = imgInfo.imgHeight;
$("#" + hidId).val(imgInfo.imgName);
var scale = 1;
//对图像进行缩放
if (width > maxSize || height > maxSize) {
if (width > height) {
width = maxSize;
height = maxSize / width * height;
scale = maxSize / width
}
else {
height = maxSize;
width = maxSize / height * width;
scale = maxSize / height;
}
}
//插入预览图
$('#' + imgPreviewId).empty().html('<img src="../upload/' + imgInfo.imgName + '" width=' + width + ' height=' + height + ' />').css({
overflow: 'hidden',
width: '120px',
height: '120px'
});
}
});
}










//验证
$("#hlGetSMSCode").bind("click",function () {
var yx = $("#txtComEmail").val();
$.ajax({
type: "post",
data: { operate: "yz",email: yx },textStatus) {
if (text != null) {

var data = eval("(" + text + ")");
if (data.flag == 'true') {

$("#tip").text(data.msg);
}
else {
$("#tip").text(data.msg);

}

// if (text == "ok") {
// $("#tip").text("格式正确......");
// }
// else {
// $("#tip").text("格式错误......");
//
// }
}


}
});

});

//修改
$("#bt_up").bind("click",textStatus) {
if (text != null) {

var data = eval("(" + text + ")");
if (data.flag == 'true') {

$("#tip").text(data.msg);
}
else {
$("#tip").text(data.msg);

}

// if (text == "ok") {
// $("#tip").text("格式正确......");
// }
// else {
// $("#tip").text("格式错误......");
//
// }
}


}
});

});


//删除
$("#bt_del").bind("click",function () {

var id = $("#txtid").val();

$.ajax({
type: "post",
data: { operate: "del",mid: id },textStatus) {
if (text != null) {

var data = eval("(" + text + ")");
if (data.flag == 'true') {

$("#tip").text(data.msg);
}
else {
$("#tip").text(data.msg);
// showTip("tip",data.msg);
}
}

// if (text == "ok") {
// $("#tip").text("格式正确......");
// }
// else {
// $("#tip").text("格式错误......");
//
// }
}
});

});

});



</script>

</head>
<body>
<form id="form1" runat="server">
<div>

<input type="text" name="username" runat="server" id="txtComEmail" placeholder="输入邮箱"
class="usr" />
<a href="javascript:void(0);" id="hlGetSMSCode" >测试</a>


<input type="text" name="username" runat="server" id="Text2" placeholder="输入邮箱"
class="usr" />

模块编号<input type="text" name="" runat="server" id="txtid" placeholder="输入编号"
class="usr" />

模块名称<input type="text" name="" runat="server" id="txt_name" placeholder="输入名称"
class="usr" />

<a href="javascript:void(0);" id="bt_up" >修改</a>

<a href="javascript:void(0);" id="bt_del" >删除</a>


<input type="text" name="username" runat="server" id="Text1" placeholder="输入邮箱"
class="usr" />
<a href="javascript:void(0);" id="mscode" >手机验证码</a>


<a id="getimg">获取头像</a>
<div class="albums"><li></li></div>

<a id="sendimg">上传图片</a>



<dl>
<dt>头像:</dt>
<dd>
<span class="photo" id="personHead">
<img id="personEditPhoto" runat="server" src="../images/user-photo.jpg" alt="" /></span>
<span class="file">
<input name="" type="file" size="50" id="filePersonHead" />
<input type="hidden" id="hidPersonHead" runat="server" />
<span style="color: #c0504d; font-size: 12px; padding-left: 5px;">建议图片尺寸120*120像素;如无法上传图片,请安装Flash插件,或者使用IE8以上浏览器</span>
</span>
</dd>
</dl>


<div id="tip" style="height: 30px; line-height: 30px; ">
</div>
</div>

<dd class="fwms" id="meetType">
<a href="#" class="sele">O2O招聘会</a><a href="#">网上招聘会</a> <a href="#">现场招聘会</a>
<input type="hidden" id="hidMeetType" value="O2O招聘会" />
</dd>


<dd id="ticketSetting">
<div id="ticketforonline">
<h6>
网上招聘会门票设置:</h6>
<div class="shmp-cont bor-b">
<div class="shmp-title">
求职方:<div class="sele">
<div class="sub" id="selPersonTicketOn" name="pOn">
<a href="javascript:void(0)">免费</a> <a href="javascript:void(0)">收费</a>
</div>

<span id="personSelectedOn" name="pOn_select">免费</span>

</div>
</div>

<div class="shmp-info" id="divPersonTicketOn" name="pOn_div">
<span>价格
<input id="txtPersonTicketOn" type="text" size="6" placeholder=" " />
元 </span>
</div>
</div>
<div class="shmp-cont">
<div class="shmp-title">
招聘方:<div class="sele">
<div class="sub" id="selCompanyTicketOn" name="cOn">
<a href="javascript:void(0)">免费</a> <a href="javascript:void(0)">收费</a>
</div>
<span id="companySelectedOn" name="cOn_select">免费</span>

</div>
</div>
<div class="shmp-info" id="divCompanyTicketOn" name="cOn_div">
<span>价格
<input name="" id="txtCompanyTicketOn" type="text" size="6" placeholder=" " />
元 </span>
</div>
</div>
</div>
<div id="ticketforoffline">
<h6>
现场招聘会门票设置:</h6>
<div class="shmp-cont bor-b">
<div class="shmp-title">
求职方:<div class="sele">
<div class="sub" id="selPersonTicketOff" name="pOff">
<a href="javascript:void(0)">免费</a> <a href="javascript:void(0)">收费</a>
</div>
<span id="personSelectedOff" name="pOff_select">免费</span>
</div>
</div>
<div class="shmp-info" id="div2" name="pOff_div">
<span>价格
<input name="" id="txtPersonTicketOff" type="text" size="6" placeholder=" " />
元 </span>
</div>
</div>
<div class="shmp-cont">
<div class="shmp-title">
招聘方:<div class="sele">
<div class="sub" id="Div1" name="cOff">
<a href="javascript:void(0)">免费</a> <a href="javascript:void(0)">收费</a>
</div>
<span id="companySelectedOff" name="cOff_select">免费</span>
</div>
</div>

<div class="shmp-info" id="divCompanyTicketOff" name="cOff_div">
<span>价格
<input name="" id="txtCompanyTicketOff" type="text" size="6" placeholder=" " />
元 </span>
</div>

</div>
</div>
</dd>

<dd id="auditSetting">
<div class="shmp-cont bor-b">
<div class="shmp-title">
求职方:<div class="sele">
<div class="sub" name="pAudit">
<a href="javascript:void(0)">不审核</a> <a href="javascript:void(0)">人工审核</a> <a href="javascript:void(0)">
智能审核</a>
</div>
<span name="pAudit_result" id="pAudit_result">不审核</span></div>
</div>
<div class="shmp-info" style="display: none;">
默认不审核,直接参会</div>
<div class="shmp-info" id="pAudit_condition" style="display: none">
<!-- 智能审核条件 -->
<dl>
<dt>最高学历:</dt>
<dd>
<select name="" id="selDegree">
<option value="">请选择</option>
<option value="">不限</option>
<option value="1">大专</option>
<option value="2">本科</option>
<option value="3">硕士</option>
<option value="4">博士</option>
<option value="5">MBA</option>
<option value="6">EMBA</option>
<option value="7">中专</option>
<option value="8">中技</option>
<option value="9">高中</option>
<option value="10">初中</option>
<option value="11">其他</option>
</select>及以上</dd>
</dl>
<dl>
<dt>工作经验:</dt>
<dd>
<select name="" id="selWorkYear">
<option value="">请选择</option>
<option value="">不限</option>
<option value="1">在读</option>
<option value="2">应届</option>
<option value="3">1年</option>
<option value="4">2年</option>
<option value="5">3年</option>
<option value="6">3~5年</option>
<option value="7">5~8年</option>
<option value="8">9年以上</option>
</select>及以上</dd>
</dl>
<dl>
<dt>专业:</dt>
<dd>
<input name="" type="text" id="txtMajor" placeholder="请选择专业" readonly="readonly" /></dd>
</dl>
<dl>
<dt>职业类别:</dt>
<dd>
<input name="" id="txtPostion" type="text" placeholder="请选择期望从事职业" /></dd>
</dl>
</div>
</div>
<div class="shmp-cont">
<div class="shmp-title">
招聘方:<div class="sele">
<div class="sub" name="cAudit">
<a href="javascript:void(0)">不审核</a> <a href="javascript:void(0)">人工审核</a> <a href="javascript:void(0)">
智能审核</a>
</div>
<span name='cAudit_result' id="cAudit_result">不审核</span>
</div>
</div>
<div class="shmp-info" style="display: none;">
默认不审核,直接参会</div>
<div class="shmp-info" id="cAudit_condition" style="display: none">
<!-- 智能审核条件 -->
<dl>
<dt>单位性质:</dt>
<dd>
<input type="text" id="txtCompanyType" readonly="readonly" />
<input type="hidden" id="hidCompanyType" />
</dd>
</dl>
<dl>
<dt>单位类别:</dt>
<dd>
<input type="text" id="txtCompanyIndustry" readonly="readonly" />
</dd>
</dl>
<dl>
<dt>单位规模:</dt>
<dd>
<select name="" id="selCompanyScale">
<option value="">请选择</option>
<option value="">不限</option>
<option value="1">10人以下</option>
<option value="2">10~49人</option>
<option value="3">50~99人</option>
<option value="4">100~199人</option>
<option value="5">200~299人</option>
<option value="6">300~499人</option>
<option value="7">500~799</option>
<option value="8">800~999人</option>
<option value="9">11000~1999人</option>
<option value="10">2000~4999人</option>
<option value="11">5000人以上</option>
</select>
及以上</dd>
</dl>
</div>
</div>
</dd>




<div id="petsimage">
<a href="#a">a</a>
<a href="#b">b</a>
<a href="#c">c</a>
</div>


<dl id="dlPlace">
<dt><i>*</i>招聘会地点:</dt>
<dd class="title" id="city_select">
<select class="prov" id="prov">
</select>
<select class="city" id="city" disabled="disabled">
</select>
<select class="dist" id="dist" disabled="disabled">
</select>
<input name="" id="txtPlace" type="text" placeholder="现场招聘会,参会地址" maxlength="50" /><br />
<a href="javascript:void(0);" id="hlShowMap">[设置地图坐标]</a>&nbsp; <span id="spanPositionTip"
class="right-tip red" style="display: none">无法定位地图坐标,请手动设置招聘会召开地点。</span>
</dd>
</dl>



<dd>
<!--,minDate:'6:00',maxDate:'12:00'-->
<input name="" id="txtDate" type="text" size="24" placeholder="请选择日期" readonly="true"
onfocus="WdatePicker({doubleCalendar:true,dateFmt:'yyyy-MM-dd',minDate:'%y-%M-{%d+1}',maxDate:'%y-{%M+6}-%d'})" />
-
<input name="" id="txtBeginTime" type="text" size="10" placeholder="开始时间" readonly="true"
onfocus="WdatePicker({dateFmt:'H:mm'})" />

<input name="" id="txtEndTime" type="text" size="10" placeholder="结束时间" readonly="true"
onfocus="WdatePicker({dateFmt:'H:mm',minDate:'#F{$dp.$D(\'txtBeginTime\',{H:1});}',maxDate:'#F{$dp.$D(\'txtBeginTime\',{H:24});}'})" /></dd>

<div id="wl"><li class="sele">aa</li><li>vv</li> </div>

</form>
</body>

</html>

B.test.ashx的代码

<%@ WebHandler Language="C#" Class="test" %> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using System.Data; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Text.RegularExpressions; public class test : IHttpHandler { private double imgWidth = 300; private double imgHeight = 200; public void ProcessRequest(HttpContext context) { string opt = context.Request["operate"]; if (opt == "yz") { string yx = context.Request["email"]; string emailStr = @"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$"; Regex emailReg = new Regex(emailStr); if (emailReg.IsMatch(yx)) // 手机号码匹配 { //context.Response.Write("ok"); context.Response.Write("{'flag':'true','msg':'格式正确'}"); } else // 邮箱匹配 { //context.Response.Write("no"); context.Response.Write("{'flag':'false','msg':'格式错误'}"); //return; } } //查询头像 else if (opt == "getPicList") { string UserId = context.Request["userid"].ToString(); string uploadUrl = "~/uploads/" + UserId + ""; List<FileItem> list = GetItems(uploadUrl); var Json = Newtonsoft.Json.JsonConvert.SerializeObject(list.Select( t => new { name = t.Name,url = "uploads/" + UserId + "/" + t.Name })); context.Response.Write(Json); } else if (opt == "del") { string id = context.Request["mid"]; CodeModel.BLL.modelinfo Modelbll = new CodeModel.BLL.modelinfo(); CodeModel.Model.modelinfo modelModel = new CodeModel.Model.modelinfo(); modelModel = Modelbll.GetModel(int.Parse(id.ToString())); if (modelModel == null) { context.Response.Write("{'flag':'false','msg':'编号不存在!'}"); return; } else { bool k = Modelbll.Delete(int.Parse(id)); if (k == true) { context.Response.Write("{'flag':'true','msg':'删除成功'}"); } else { context.Response.Write("{'flag':'false','msg':'删除失败'}"); return; } } } else if (opt == "uploadImage") { if (context.Request.Files.Count > 0) { string upfilename = null; string revalue = ""; HttpPostedFile uploadFile = context.Request.Files[0]; if (uploadFile.ContentLength > 0) { var oldImg = context.Request["oldImg"]; if (!string.IsNullOrEmpty(oldImg)) { if (File.Exists(context.Server.MapPath("~/uploads/wl/" + oldImg))) { File.Delete(context.Server.MapPath("~/uploads/wl/" + oldImg)); } } //保存文件 string exname = Path.GetExtension(uploadFile.FileName); string fileName = Guid.NewGuid().ToString(); upfilename = string.Format("{0}{1}",fileName,exname); string newUpfilename = string.Format("{0}{1}",fileName + "_MN",exname); string filepath = context.Server.MapPath("~/uploads/wl/" + upfilename); string newFilePath = context.Server.MapPath("~/uploads/wl/" + newUpfilename); uploadFile.SaveAs(filepath); //System.Drawing.Image initImage = System.Drawing.Image.FromFile(filepath,true); this.ZoomPic(filepath,newFilePath,300,200); File.Delete(filepath); revalue = "{'imgName':'" + newUpfilename + "','imgWidth':'" + imgWidth + "','imgHeight':'" + imgHeight + "'}"; //initImage.Dispose(); } else { throw new Exception("null file"); } //回传存储的文件名 HttpContext.Current.Response.Write(revalue.ToString()); } else { HttpContext.Current.Response.Write(" "); } } else if (opt == "update") { string id = context.Request["id"]; string mname = context.Request["name"]; CodeModel.BLL.modelinfo Modelbll = new CodeModel.BLL.modelinfo(); CodeModel.Model.modelinfo modelModel = new CodeModel.Model.modelinfo(); modelModel = Modelbll.GetModel(int.Parse(id.ToString())); if (modelModel == null) { context.Response.Write("{'flag':'false','msg':'编号不存在!'}"); return; } else { modelModel.Id = int.Parse(id); modelModel.Model_name = mname; bool k = Modelbll.Update(modelModel); if (k == true) { context.Response.Write("{'flag':'true','msg':'修改成功'}"); } else { context.Response.Write("{'flag':'false','msg':'修改失败'}"); return; } } } } /// <summary> /// 对上传图片进行等比缩放 /// </summary> /// <param name="fromFile">获取文件流Stream</param> /// <param name="fileSaveUrl">缩略图保存完整路径</param> /// <param name="targetWidth">模板宽度</param> /// <param name="targetHeight">模板高度</param> public void ZoomPic(string sourceFileUrl,string fileSaveUrl,System.Double targetWidth,System.Double targetHeight) { //原始图片获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromFile(sourceFileUrl,true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= targetWidth && initImage.Height <= targetHeight) { //保存 initImage.Save(fileSaveUrl,System.Drawing.Imaging.ImageFormat.Jpeg); imgWidth = initImage.Width; imgHeight = initImage.Height; } else { //缩略图宽、高计算 double newWidth = initImage.Width; double newHeight = initImage.Height; //宽大于高或宽等于高(横图或正方) if (initImage.Width > initImage.Height || initImage.Width == initImage.Height) { //如果宽大于模版 if (initImage.Width > targetWidth) { //宽按模版,高按比例缩放 newWidth = targetWidth; newHeight = initImage.Height * (targetWidth / initImage.Width); imgWidth = newWidth; imgHeight = newHeight; } } //高大于宽(竖图) else { //如果高大于模版 if (initImage.Height > targetHeight) { //高按模版,宽按比例缩放 newHeight = targetHeight; newWidth = initImage.Width * (targetHeight / initImage.Height); } } imgWidth = newWidth; imgHeight = newHeight; //生成新图 //新建一个bmp图片 System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth,(int)newHeight); //新建一个画板 System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage); //设置质量 newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //置背景色 newG.Clear(Color.White); //画图 newG.DrawImage(initImage,new System.Drawing.Rectangle(0,newImage.Width,newImage.Height),initImage.Width,initImage.Height),System.Drawing.GraphicsUnit.Pixel); //保存缩略图 newImage.Save(fileSaveUrl,System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 newG.Dispose(); newImage.Dispose(); } initImage.Dispose(); } /// <summary> /// 文件信息实体 /// </summary> public class FileItem { // Properties /// <summary> /// 创建日期 /// </summary> public DateTime CreationDate { get; set; } /// <summary> /// 文件计数 /// </summary> public long FileCount { get; set; } /// <summary> /// 文件全名,含路径 /// </summary> public string FullName { get; set; } /// <summary> /// 是否为文件夹 /// </summary> public bool IsFolder { get; set; } /// <summary> /// 最后打开时间 /// </summary> public DateTime LastAccessDate { get; set; } /// <summary> /// 最后修改时间 /// </summary> public DateTime LastWriteDate { get; set; } /// <summary> /// 文件名 /// </summary> public string Name { get; set; } /// <summary> /// 扩展名 /// </summary> public string Ext { get; set; } /// <summary> /// 文件大小 /// </summary> public long Size { get; set; } /// <summary> /// 子文件夹数 /// </summary> public long SubFolderCount { get; set; } /// <summary> /// 虚路径 相对于网站根的路径 /// </summary> public string VirtualPath { get; set; } } /// <summary> /// 获取指定目录下所有文件列表 /// </summary> /// <param name="virPath"></param> /// <returns></returns> public static List<FileItem> GetItems(string virPath) { List<FileItem> list = new List<FileItem>(); string phyPath = HttpContext.Current.Server.MapPath(virPath); if (Directory.Exists(phyPath)) { string[] files = Directory.GetFiles(phyPath); foreach (string str in files) { FileItem item = new FileItem(); FileInfo info2 = new FileInfo(str); item.Name = info2.Name; item.FullName = info2.FullName; item.CreationDate = info2.CreationTime; item.IsFolder = false; item.Size = info2.Length; item.Ext = info2.Extension.TrimStart('.'); item.VirtualPath = virPath + info2.Name; item.LastWriteDate = info2.LastWriteTime; list.Add(item); } } return list; } public bool IsReusable { get { return false; } } }

猜你在找的Ajax相关文章