jquery+一般处理程序实现图片异步上传
前段:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadImage.aspx.cs" Inherits="TestFullCalendar_web.UploadImage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>上传照片</title>
<script src="fullCalendar/lib/jquery.min.js" type="text/javascript"></script>
<script src="fullCalendar/lib/jQuery.form.js" type="text/javascript"></script>
<script type="text/javascript">
function uploadImage() {
//判断是否有选择上传文件
var imgPath = $("#uploadFile").val();
if (imgPath == "") {
alert("请选择上传图片!");
return;
}
//判断上传文件的后缀名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("请选择图片文件");
return;
}
$("#form1").ajaxSubmit({
// type: "POST",
url: "handler/UploadImageHandler.ashx",
// data: { imgPath: $("#uploadFile").val() },
// cache: false,
type: "post",
dataType: "text",
resetForm: "true",
success: function (data) {
alert("上传成功");
$("#imgDiv").empty();
$("#imgDiv").html(data);
$("#imgDiv").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="uploadFile" name="uploadFile" />
<input type="button" id="btnUpload" value="确定" οnclick="uploadImage()" />
<div id="imgDiv">
</div>
</form>
</body>
</html>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Text;
using System.IO;
namespace TestFullCalendar_web.handler
{
/// <summary>
/// UploadImageHandler 的摘要说明
/// </summary>
public class UploadImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
//不知道为什么获取不到
HttpPostedFile file = context.Request.Files["uploadFile"];
string path = "UploadImgs\\";
if (file != null)
{
if (file.InputStream.Length != 0)
{
string fileName = Path.GetFileName(file.FileName); //原文件名
string mapPath = context.Server.MapPath("~");
string savePath = mapPath + "\\" + path + fileName;
file.SaveAs(savePath);
//上传成功后显示IMG文件
StringBuilder sb = new StringBuilder();
sb.Append("<img id=\"imgUpload\" src=\"" + path.Replace("\\", "/") + fileName + "\" />");
context.Response.Write(sb.ToString());
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}