ashx,中返回类型设置成 json,plain时,返回的Json代码解析都出错,调试发现实际返回的除了json字符串外还有,其他html或xml导致无法解析成json对象
function UploadFile(elmFlag) { $.ajaxFileUpload({ url: '/FileUpload.ashx', secureuri: false, fileElementId: "fu" + elmFlag, dataType: "json", success: function (data, status) { if (data.Code == 200) { alert( unescape(data.Name)); } else { alert( unescape(data.Msg)); } $("#c_" + elmFlag).empty(); $("#c_" + elmFlag).append("<input type='file' name='fu" + elmFlag + "' id='fu" + elmFlag + "' onchange=\"UploadFile('" + elmFlag + "')\" />"); }, error: function (data, status, e) { alert("错误:上传组件错误,请检察网络!"); } }); }
服务器端
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.IO; using System.Web.Hosting; using F.Studio.Common; using Microsoft.Practices.Unity; using JLMFG.Doc.BLL; using JLMFG.Doc.Domain; namespace JLMFG.Doc.Web { /// <summary> /// FileUpload 的摘要说明 /// </summary> public class FileUpload : IHttpHandler,IBuildUp { static readonly string C_FileRoot = "/Files/"; [Dependency] public doc_DocManager DocMgr { get; set; } private HttpRequest Request { get; set; } private HttpResponse Response { get; set; } private JavaScriptSerializer Serializer { get; set; } public void ProcessRequest(HttpContext context) { Request = context.Request; Response = context.Response; Serializer = new JavaScriptSerializer(); Response.ContentType = "text/html"; Response.Expires = -1; try { if (Request.Files.Count <= 0) throw new Exception("没有文件上传!"); SaveFile(); } catch (Exception ex) { var resp=new UploadResponse(){Code=400,Msg=StringHelper.Escape(ex.Message)}; Response.Write(Serializer.Serialize(resp)); } Response.End(); } private void SaveFile() { var file = Request.Files[0]; var ext = Path.GetExtension(file.FileName); //确保目录存在 string path = C_FileRoot + DateTime.Now.ToString("yyyy-MM-dd") + "/"; if (!Directory.Exists( HostingEnvironment.MapPath(path))) { Directory.CreateDirectory(HostingEnvironment.MapPath(path)); } //合成文件名 var filename= path + Guid.NewGuid().ToString("N").Substring(0,8) + ext; var resp = new UploadResponse(); resp.MIME = file.ContentType; resp.Size = file.ContentLength / 1024; resp.Name =StringHelper.Escape( Path.GetFileNameWithoutExtension(file.FileName)); resp.Path =StringHelper.Escape( filename); resp.Code = 200; resp.Msg = "Success"; //保持文件 file.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath(filename)); Response.Write(Serializer.Serialize(resp)); } public bool IsReusable { get { return false; } } public class UploadResponse { public int Code { get; set; } public string Msg { get; set; } public string Path { get; set; } public string Name { get; set; } public long Size { get; set; } public string MIME { get; set; } } } }