//Demo页面和官方的页面差不多
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload
(
{
url:'DoAjaxUpLoad.ashx',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form name="form" action="" method="POST" enctype="multipart/form-data" runat="server">
<table cellpadding="0" cellspacing="0" >
<thead>
<tr>
<th>Please select a file and click Upload button</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45" name="fileToUpload" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button id="buttonUpload" οnclick="return ajaxFileUpload();">Upload</button>
</td>
</tr>
</tfoot>
</table>
</form>
</body>
</html>
//使用.net一般处理程序<%@ WebHandler Language="C#" Class="DoAjaxUpLoad" %>
using System;
using System.Web;
public class DoAjaxUpLoad : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";//****这里是重要的地方,必须以html形式返回,在客户端才能使用ajaxfileupload正确处理。刚开始没注意这个问题,一直使用默认值“text/plain”,客户端死活不能正确处理,这个小问题耗了我两天的时间。后来换成.aspx页面处理,一下就成功了。这就让人纳闷了:aspx能处理,ashx就不能处理吗?不太可能吧!aspx以html形式返回客户端,那么ashx也必须以html形式返回客户端,才能被ajaxfileupload正确处理啊。一试,果然推测不错!拿出来和大家共享!!
string error = "";
string result = "{/"error/":/"/",/"msg/":/"fileszie:10mb,filename:new text/"}";
HttpContext.Current.Response.Write(result);
HttpContext.Current.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}