$.ajaxFileUpload({ type: "post", //请求类型:post或get,当要使用data提交自定义参数时一定要设置为post url: "/Shared/Upload", //文件上传的服务器端请求地址secureuri: false, //是否启用安全提交,一般默认为false就行,不用特殊处理fileElementId: "filePicture", //文件上传控件的id<input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" /> dataType: "json", //返回值类型,一般设置为json,还支持htmlxmlscript类型data: { "id": "1", "name": "test" },//用于post请求提交自定义参数success: function (data, status) { //服务器成功响应处理函数},error: function (data, status, e) {//服务器响应失败处理函数}});首先在页面添加对JQuery及ajaxFileUpload的引用,这里的JQuery用的2.1.4版本,经测试用各个版本基本没什么影响。
function filePictureChange() {$.ajaxFileUpload({url: "/Shared/Upload", //用于文件上传的服务器端请求地址type: "post",secureuri: false, //一般设置为falsefileElementId: "filePicture", //文件上传空间的id属性dataType: "json", //返回值类型 一般设置为jsonsuccess: function (data, status) { //服务器成功响应处理函数alert(data.fileName);alert(data.filePath);alert(data.fileSize);},error: function (data, status, e){ //服务器响应失败处理函数alert(e);}});};后台控制器处理方法如下,使用MD5处理,判断文件是否已经存在,避免文件重复上传。
/// <summary>/// 附件上传/// </summary>/// <returns></returns>public ActionResult Upload(){HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet);MD5 md5Hasher = new MD5CryptoServiceProvider();/*计算指定Stream对象的哈希值*/byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream);/*由以连字符分隔的十六进制对构成的String,其中每一对表示value中对应的元素;例如“F-2C-4A”*/string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", "");string FileEextension = Path.GetExtension(files[0].FileName);string uploadDate = DateTime.Now.ToString("yyyyMMdd");string virtualPath = string.Format("/Data/ComponentAttachments/{0}/{1}{2}", uploadDate, strHashData, FileEextension);string fullFileName = Server.MapPath(virtualPath);//创建文件夹,保存文件 string path = Path.GetDirectoryName(fullFileName);Directory.CreateDirectory(path);if (!System.IO.File.Exists(fullFileName)){files[0].SaveAs(fullFileName);}string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\") - 1);string fileSize = GetFileSize(files[0].ContentLength);return Json(new { FileName = fileName, FilePath = virtualPath, FileSize = fileSize }, "text/html", JsonRequestBehavior.AllowGet);}/// <summary>/// 获取文件大小/// </summary>/// <param name="bytes"></param>/// <returns></returns>private string GetFileSize(long bytes){long kblength = 1024;long mbLength = 1024 * 1024;if (bytes < kblength)return bytes.ToString() + "B";if (bytes < mbLength)return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB";elsereturn decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB";}2 ajaxFileUpload使用过程中的一些问题
解决方法:
经测试handlerError只在jquery-1.4.2之前的版本中存在,以后版本中都没有这个函数了,因此在将handleError这个函数复制到ajaxFileUpload.js中,就行了
uploadHttpData: function (r, type) {var data = !type;data = type == "xml" || data ? r.responseXML : r.responseText;// If the type is "script", eval it in global contextif (type == "script")jQuery.globalEval(data);// Get the JavaScript object, if JSON is used.if (type == "json")eval("data = " + data);//eval("data = "" + data + """);// evaluate scripts within htmlif (type == "html")jQuery("<div>").html(data).evalScripts();return data;},handleError: function (s, xhr, status, e) {// If a local callback was specified, fire itif (s.error) {s.error.call(s.context || s, xhr, status, e);}// Fire the global callbackif (s.global) {(s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);}}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。