上传文件是常要处理的事情,使用ajaxFileUpload.js处理比较方便,这里的ajaxFileUpload.js文件修改过的,
Html部分
<input type="file" id="fu_UploadFile" name="fu_UploadFile" value="" title="上传附件">
<input type="button" value="上传" onclick="upload()" />
JS部分:
function upload() {
var path = document.getElementById("fu_UploadFile").value;
if ($.trim(path) == "") { alert("请选择要上传的文件"); return; }
console.log("test");</span><span style="color: #0000ff;">var</span> result_msg = ""<span style="color: #000000;">;
$.ajaxFileUpload({
url: </span>'/UpFile.ashx', <span style="color: #008000;">//</span><span style="color: #008000;">这里是服务器处理的代码</span>
type: 'post'<span style="color: #000000;">,
secureuri: </span><span style="color: #0000ff;">false</span>, <span style="color: #008000;">//</span><span style="color: #008000;">一般设置为false</span>
fileElementId: 'fu_UploadFile', <span style="color: #008000;">//</span><span style="color: #008000;"> 上传文件的id、name属性名</span>
dataType: 'json', <span style="color: #008000;">//</span><span style="color: #008000;">返回值类型,一般设置为json、application/json</span>
data: {}, <span style="color: #008000;">//</span><span style="color: #008000;">传递参数到服务器</span>
success: <span style="color: #0000ff;">function</span><span style="color: #000000;"> (data, status) {
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (data.Result) {
alert(</span>"文件成功处理完成!" +<span style="color: #000000;"> data.FileName);
} </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
alert(</span>"文件成功处理出错!原因:" +<span style="color: #000000;"> data.ErrorMessage);
}
},
error: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (data, status, e) {
alert(</span>"错误:上传组件错误,请检察网络!"<span style="color: #000000;">);
}
});
}</span></pre>
服务器:
/// <summary>
/// UpFile 的摘要说明
/// </summary>
public class UpFile : IHttpHandler
{</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> ProcessRequest(HttpContext context)
{
context.Response.ContentType </span>= <span style="color: #800000;">"</span><span style="color: #800000;">text/plain</span><span style="color: #800000;">"</span><span style="color: #000000;">;
UpFileResult result </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> UpFileResult();
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">
{
HttpPostedFile _upfile </span>= context.Request.Files[<span style="color: #800000;">"</span><span style="color: #800000;">fu_UploadFile</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #0000ff;">if</span> (_upfile == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
{
</span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> Exception(<span style="color: #800000;">"</span><span style="color: #800000;">请先选择文件!</span><span style="color: #800000;">"</span><span style="color: #000000;">);
}
</span><span style="color: #0000ff;">else</span><span style="color: #000000;">
{
</span><span style="color: #0000ff;">string</span> fileName = _upfile.FileName;<span style="color: #008000;">/*</span><span style="color: #008000;">获取文件名: C:\Documents and Settings\Administrator\桌面\123.jpg</span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">string</span> suffix = fileName.Substring(fileName.LastIndexOf(<span style="color: #800000;">"</span><span style="color: #800000;">.</span><span style="color: #800000;">"</span>) + <span style="color: #800080;">1</span>).ToLower();<span style="color: #008000;">/*</span><span style="color: #008000;">获取后缀名并转为小写: jpg</span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">int</span> bytes = _upfile.ContentLength;<span style="color: #008000;">//</span><span style="color: #008000;">获取文件的字节大小
</span><span style="color: #008000;">//if (!(suffix == "jpg" || suffix == "gif" || suffix == "png"|| suffix == "jpeg"))
throw new Exception("只能上传JPE,GIF,PNG文件");
if (bytes > * *)
throw new Exception("文件最大只能传10M");
string newfileName = DateTime.Now.ToString("yyyyMMddHHmmss");
string fileDir = HttpContext.Current.Server.MapPath("~/upfiles/");
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
result.FileName = fileName;
string saveDir = fileDir + newfileName + "." + suffix;
result.FileURL = "~/upfiles/" + newfileName + "." + suffix;
_upfile.SaveAs(result.FileURL);//保存图片 }
}
catch (System.Exception ex)
{
result.Result = false;
result.ErrorMessage = ex.Message;
}
context.Response.Write(JsonHelper.SerializeObject(result));}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">bool</span><span style="color: #000000;"> IsReusable
{
</span><span style="color: #0000ff;">get</span><span style="color: #000000;">
{
</span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;
}
} </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> UpFileResult <span style="color: #008000;">//</span><span style="color: #008000;">: AshxCommonResult</span>{
public bool Result { get; set; }
public string ErrorMessage { get; set; }
public string FileName { get; set; }
public string FileURL { get; set; }
}
ajaxfileupload.js
jQuery.extend({handleError: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (s, xhr, status, e) {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> If a local callback was specified, fire it</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;"> (s.error) {
s.error.call(s.context </span>||<span style="color: #000000;"> s, xhr, status, e);
}
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Fire the global callback</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;"> (s.global) {
(s.context </span>? jQuery(s.context) : jQuery.event).trigger("ajaxError"<span style="color: #000000;">, [xhr, s, e]);
}
},
createUploadIframe: </span><span style="color: #0000ff;">function</span><span style="color: #000000;">(id, uri)
{
</span><span style="color: #008000;">//</span><span style="color: #008000;">create frame</span>
<span style="color: #0000ff;">var</span> frameId = 'jUploadFrame' +<span style="color: #000000;"> id;
</span><span style="color: #0000ff;">var</span> iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'<span style="color: #000000;">;
</span><span style="color: #0000ff;">if</span><span style="color: #000000;">(window.ActiveXObject)
{
</span><span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">typeof</span> uri== 'boolean'<span style="color: #000000;">){
iframeHtml </span>+= ' src="' + 'javascript:false' + '"'<span style="color: #000000;">; }
</span><span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">typeof</span> uri== 'string'<span style="color: #000000;">){
iframeHtml </span>+= ' src="' + uri + '"'<span style="color: #000000;">; }
}
iframeHtml </span>+= ' />'<span style="color: #000000;">;
jQuery(iframeHtml).appendTo(document.body); </span><span style="color: #0000ff;">return</span> jQuery('#' + frameId).get(0<span style="color: #000000;">);
}, createUploadForm: </span><span style="color: #0000ff;">function</span><span style="color: #000000;">(id, fileElementId, data)
{
</span><span style="color: #008000;">//</span><span style="color: #008000;">create form </span>
<span style="color: #0000ff;">var</span> formId = 'jUploadForm' +<span style="color: #000000;"> id;
</span><span style="color: #0000ff;">var</span> fileId = 'jUploadFile' +<span style="color: #000000;"> id;
</span><span style="color: #0000ff;">var</span> form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'<span style="color: #000000;">);
</span><span style="color: #0000ff;">if</span><span style="color: #000000;">(data)
{
</span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> i <span style="color: #0000ff;">in</span><span style="color: #000000;"> data)
{
jQuery(</span>'<input type="hidden" name="' + i + '" value="' + data[i] + '" />'<span style="color: #000000;">).appendTo(form);
}
}
</span><span style="color: #0000ff;">var</span> oldElement = jQuery('#' +<span style="color: #000000;"> fileElementId);
</span><span style="color: #0000ff;">var</span> newElement =<span style="color: #000000;"> jQuery(oldElement).clone();
jQuery(oldElement).attr(</span>'id'<span style="color: #000000;">, fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form); </span><span style="color: #008000;">//</span><span style="color: #008000;">set attributes</span>
jQuery(form).css('position', 'absolute'<span style="color: #000000;">);
jQuery(form).css(</span>'top', '-1200px'<span style="color: #000000;">);
jQuery(form).css(</span>'left', '-1200px'<span style="color: #000000;">);
jQuery(form).appendTo(</span>'body'<span style="color: #000000;">);
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> form;
}, ajaxFileUpload: </span><span style="color: #0000ff;">function</span><span style="color: #000000;">(s) {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO introduce global settings, allowing the client to modify them for all requests, not only timeout </span>
s =<span style="color: #000000;"> jQuery.extend({}, jQuery.ajaxSettings, s);
</span><span style="color: #0000ff;">var</span> id = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date().getTime()
</span><span style="color: #0000ff;">var</span> form = jQuery.createUploadForm(id, s.fileElementId, (<span style="color: #0000ff;">typeof</span>(s.data)=='undefined'?<span style="color: #0000ff;">false</span><span style="color: #000000;">:s.data));
</span><span style="color: #0000ff;">var</span> io =<span style="color: #000000;"> jQuery.createUploadIframe(id, s.secureuri);
</span><span style="color: #0000ff;">var</span> frameId = 'jUploadFrame' +<span style="color: #000000;"> id;
</span><span style="color: #0000ff;">var</span> formId = 'jUploadForm' +<span style="color: #000000;"> id;
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Watch for a new set of requests</span>
<span style="color: #0000ff;">if</span> ( s.global && ! jQuery.active++<span style="color: #000000;"> )
{
jQuery.event.trigger( </span>"ajaxStart"<span style="color: #000000;"> );
}
</span><span style="color: #0000ff;">var</span> requestDone = <span style="color: #0000ff;">false</span><span style="color: #000000;">;
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Create the request object</span>
<span style="color: #0000ff;">var</span> xml =<span style="color: #000000;"> {}
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> ( s.global )
jQuery.event.trigger(</span>"ajaxSend"<span style="color: #000000;">, [xml, s]);
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Wait for a response to come back</span>
<span style="color: #0000ff;">var</span> uploadCallback = <span style="color: #0000ff;">function</span><span style="color: #000000;">(isTimeout)
{
</span><span style="color: #0000ff;">var</span> io =<span style="color: #000000;"> document.getElementById(frameId);
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">
{
</span><span style="color: #0000ff;">if</span><span style="color: #000000;">(io.contentWindow)
{
xml.responseText </span>= io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:<span style="color: #0000ff;">null</span><span style="color: #000000;">;
xml.responseXML </span>= io.contentWindow.document.XMLDocument?<span style="color: #000000;">io.contentWindow.document.XMLDocument:io.contentWindow.document; }</span><span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span><span style="color: #000000;">(io.contentDocument)
{
xml.responseText </span>= io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:<span style="color: #0000ff;">null</span><span style="color: #000000;">;
xml.responseXML </span>= io.contentDocument.document.XMLDocument?<span style="color: #000000;">io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(e)
{
jQuery.handleError(s, xml, </span><span style="color: #0000ff;">null</span><span style="color: #000000;">, e);
}
</span><span style="color: #0000ff;">if</span> ( xml || isTimeout == "timeout"<span style="color: #000000;">)
{
requestDone </span>= <span style="color: #0000ff;">true</span><span style="color: #000000;">;
</span><span style="color: #0000ff;">var</span><span style="color: #000000;"> status;
</span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
status </span>= isTimeout != "timeout" ? "success" : "error"<span style="color: #000000;">;
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Make sure that the request was successful or notmodified</span>
<span style="color: #0000ff;">if</span> ( status != "error"<span style="color: #000000;"> )
{
</span><span style="color: #008000;">//</span><span style="color: #008000;"> process the data (runs the xml through httpData regardless of callback)</span>
<span style="color: #0000ff;">var</span> data =<span style="color: #000000;"> jQuery.uploadHttpData( xml, s.dataType );
</span><span style="color: #008000;">//</span><span style="color: #008000;"> If a local callback was specified, fire it and pass it the data</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;"> ( s.success )
s.success( data, status ); </span><span style="color: #008000;">//</span><span style="color: #008000;"> Fire the global callback</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;">( s.global )
jQuery.event.trigger( </span>"ajaxSuccess"<span style="color: #000000;">, [xml, s] );
} </span><span style="color: #0000ff;">else</span><span style="color: #000000;">
jQuery.handleError(s, xml, status);
} </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(e)
{
status </span>= "error"<span style="color: #000000;">;
jQuery.handleError(s, xml, status, e);
} </span><span style="color: #008000;">//</span><span style="color: #008000;"> The request was completed</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;">( s.global )
jQuery.event.trigger( </span>"ajaxComplete"<span style="color: #000000;">, [xml, s] ); </span><span style="color: #008000;">//</span><span style="color: #008000;"> Handle the global AJAX counter</span>
<span style="color: #0000ff;">if</span> ( s.global && ! --<span style="color: #000000;">jQuery.active )
jQuery.event.trigger( </span>"ajaxStop"<span style="color: #000000;"> ); </span><span style="color: #008000;">//</span><span style="color: #008000;"> Process result</span>
<span style="color: #0000ff;">if</span><span style="color: #000000;"> ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(</span><span style="color: #0000ff;">function</span><span style="color: #000000;">()
{ </span><span style="color: #0000ff;">try</span><span style="color: #000000;">
{
jQuery(io).remove();
jQuery(form).remove(); } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(e)
{
jQuery.handleError(s, xml, </span><span style="color: #0000ff;">null</span><span style="color: #000000;">, e);
} }, </span>100<span style="color: #000000;">) xml </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;"> }
}
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Timeout checker</span>
<span style="color: #0000ff;">if</span> ( s.timeout > 0<span style="color: #000000;"> )
{
setTimeout(</span><span style="color: #0000ff;">function</span><span style="color: #000000;">(){
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Check to see if the request is still happening</span>
<span style="color: #0000ff;">if</span>( !requestDone ) uploadCallback( "timeout"<span style="color: #000000;"> );
}, s.timeout);
}
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">
{ </span><span style="color: #0000ff;">var</span> form = jQuery('#' +<span style="color: #000000;"> formId);
jQuery(form).attr(</span>'action'<span style="color: #000000;">, s.url);
jQuery(form).attr(</span>'method', 'POST'<span style="color: #000000;">);
jQuery(form).attr(</span>'target'<span style="color: #000000;">, frameId);
</span><span style="color: #0000ff;">if</span><span style="color: #000000;">(form.encoding)
{
jQuery(form).attr(</span>'encoding', 'multipart/form-data'<span style="color: #000000;">);
}
</span><span style="color: #0000ff;">else</span><span style="color: #000000;">
{
jQuery(form).attr(</span>'enctype', 'multipart/form-data'<span style="color: #000000;">);
}
jQuery(form).submit(); } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(e)
{
jQuery.handleError(s, xml, </span><span style="color: #0000ff;">null</span><span style="color: #000000;">, e);
} jQuery(</span>'#' +<span style="color: #000000;"> frameId).load(uploadCallback );
</span><span style="color: #0000ff;">return</span> {abort: <span style="color: #0000ff;">function</span><span style="color: #000000;"> () {}}; }, uploadHttpData: </span><span style="color: #0000ff;">function</span><span style="color: #000000;">( r, type ) {
</span><span style="color: #0000ff;">var</span> data = !<span style="color: #000000;">type;
data </span>= type == "xml" || data ?<span style="color: #000000;"> r.responseXML : r.responseText;
</span><span style="color: #008000;">//</span><span style="color: #008000;"> If the type is "script", eval it in global context</span>
<span style="color: #0000ff;">if</span> ( type == "script"<span style="color: #000000;"> )
jQuery.globalEval( data );
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Get the JavaScript object, if JSON is used.</span>
<span style="color: #0000ff;">if</span> ( type == "json"<span style="color: #000000;"> )
</span><span style="color: #0000ff;">var</span> reg = /<pre.+?>(.+)<\/pre>/<span style="color: #000000;">g;
</span><span style="color: #0000ff;">var</span> result =<span style="color: #000000;"> data.match(reg);
data </span>= RegExp.$1<span style="color: #000000;">;
eval( </span>"data = " +<span style="color: #000000;"> data );
</span><span style="color: #008000;">//</span><span style="color: #008000;"> evaluate scripts within html</span>
<span style="color: #0000ff;">if</span> ( type == "html"<span style="color: #000000;"> )
jQuery(</span>"<div>"<span style="color: #000000;">).html(data).evalScripts(); </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> data;
}})