.net MVC 项目中 上传或者处理进度获取方案
首先讲下思路
就是利用js轮询定时的给后台发送数据
话不多说看代码
---------
以下是相关方法
var t function timedCount() { $.ajax({ type: 'get', url: '../../TMS.Service/OrderImport/GetImportProcess?cacheKey=' + cacheKey, dataType: 'json', success: function (data) { if (data.status) { //读取一次销毁一次 $('#redMsg').html("" + data.msg + ""); } }, }); t = setTimeout("timedCount()", 2000) }
cacheKey = guid();
var cacheKey = "";
function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
------接下来 看下后台代码
//////获取执行进度查询 /// /// [HttpGet] public ActionResult GetImportProcess(string cacheKey=null) { try { var result = new OrderImportBiz().GetImportProcess(cacheKey); return new ReponseModel { status = !string.IsNullOrEmpty(result), msg = result }; } catch (Exception ex) { return new ReponseModel { status = false, msg = $"
获取进度失败了{ex.Message}!" }; } }
CacheHelper.SetCache(MSG_CACHE_KEY, "正在准备向系统申请添加数据!");
////// 缓存帮助类 /// public class CacheHelper { /// /// 获取数据缓存 /// /// 键 public static object GetCache(string cacheKey) { var objCache = HttpRuntime.Cache.Get(cacheKey); return objCache; } /// /// 设置数据缓存 /// public static void SetCache(string cacheKey, object objObject) { var objCache = HttpRuntime.Cache; if (objCache!=null && objObject!=null) { objCache.Insert(cacheKey, objObject); } } /// /// /// /// /// /// 单位秒 默认7200秒 public static void SetCache(string cacheKey, object objObject, int timeout = 2) { try { if (objObject == null) return; var objCache = HttpRuntime.Cache; //相对过期 //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null); //绝对过期时间 objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null); } catch (Exception) { //throw; } } /// /// 移除指定数据缓存 /// public static void RemoveAllCache(string cacheKey) { var cache = HttpRuntime.Cache; cache.Remove(cacheKey); } /// /// 移除全部缓存 /// public static void RemoveAllCache() { var cache = HttpRuntime.Cache; var cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } } }