第一种方式是通过插件AjaxForm的方式
前台(html页):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>上传图片</title>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../Scripts/AjaxForm.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// 等待图片
$("#btnUpload").after("<img id='waitImg' src='../Images/ico_loading2.gif' style='height:20px;margin-left:15px' />");
// 用插件AjaxForm实现上传
$("#btnUpload").click(function () {
$("#frm").ajaxSubmit({
url: "imageUploadProce.ashx",
type: "post",
success: function (suc) {
// 移除图片(到这一步说明已经返回了数据)
$("#waitImg").remove();
if (suc == 'no') {
alert('上传失败');
} else {
$("#img").attr("src", suc);
}
},
error: function (err) {
alert('上传失败' + err);
}
});
});
});
</script>
</head>
<body>
<form id="frm" enctype="multipart/form-data">
<input type="file" name="ImageUpload" id="ImageUpload" />
<input type="button" value="上传" name="btnUpload" id="btnUpload" />
<img id="img" src="">
</form>
</body>
</html>
后台(一般处理程序):
public class imageUploadProce : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string fileType = context.Request.Files[0].ContentType.ToLower();
if (fileType == "image/jpeg" || fileType == "image/gif" || fileType == "image/png" || fileType == "image/bmp")
{
// 传递给前台的地址
string postToHtmlPath = "../Images/" + Guid.NewGuid().ToString() + context.Request.Files[0].FileName;
// 处理上传文件的地址 要转换成绝对路径才能保存到
string imgPath = context.Request.MapPath(postToHtmlPath);
// 保存在当前文件加下
HttpPostedFile postFile = context.Request.Files[0];
postFile.SaveAs(imgPath);
// 必须返回图片的相对路径 因为图片不能直接从硬盘上读取
context.Response.Write(postToHtmlPath);
}
else
{
context.Response.Write("no");
}
}
else
{
context.Response.Write("no");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}