<form method="post" enctype="multipart/form-data"> <input type="file" multiple /> <br /> <button type="button">ajax上传进度效果上传</button> <br /> <span></span> </form>
要加一个进度效果,需要用到js的定时器,定时获取上传文件的上传进度数据信息,因此这里通过js的setInterval方法来定时请求一个进度数据接口,注意用完之后需要清除这个定时器,不然一直再不断请求您接口:
$("#btnAjax02").on("click", function () { var interBar; var msg = $("#span02"); msg.html("上传中,请稍后..."); var form = document.getElementById("form02"); //console.log(form); var data = new FormData(form); $.ajax({ type: "POST", url: "/home/AjaxFileUp02", data: data, contentType: false, processData: false, success: function (data) { if (data) { msg.html(data.msg); //清除进度查询 if (interBar) { clearInterval(interBar); } } }, error: function () { msg.html("上传文件异常,请稍后重试!"); if (interBar) { clearInterval(interBar); } } }); //获取进度 interBar = setInterval(function () { $.post("/home/ProgresBar02", function (data) { if (data) { var isClearVal = true; var strArr = []; $.each(data, function (i, item) { strArr.push('文件:' + item.fileName + ",当前上传:" + item.percentBar + '<br/>'); if (item.status != 2) { isClearVal = false; } }); msg.html(strArr.join('')); if (isClearVal) { if (interBar) { clearInterval(interBar); } } } }); }, 200); });
既然上面说到单独的进度数据接口,那么我们除了上传Action外,也需要进度的Action,而这进度Action得到的上传文件数据信息必须和上传的Action一直,因此就需要用到缓存等存储数据的方式,这里我用的是MemoryCache的方式,对已netcore来说仅仅只需要在起始文件(如:Startup.cs)中添加组件服务:
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); //添加cache支持 services.AddDistributedMemoryCache(); }
然后通过构造函数注入到对应的接口Controller中去:
readonly IMemoryCache _cache; public HomeController(IOptions<MoOptions> options, ILogger<HomeController> logger, IMemoryCache cache) { this._options = options.Value; _logger = logger; _cache = cache; }
到此我们就能利用cache来存储我们上传进度信息了,来看下处理上传的Action:
private string cacheKey = "UserId_UpFile"; private string cacheKey03 = "UserId_UpFile03"; /// <summary> /// ajax上传进度效果上传 /// </summary> /// <returns></returns> [HttpPost] public async Task<JsonResult> AjaxFileUp02() { var data = new MoData { Msg = "上传失败" }; try { var files = Request.Form.Files.Where(b => b.Name == "MyPhoto02"); //非空限制 if (files == null || files.Count() <= 0) { data.Msg = "请选择上传的文件。"; return Json(data); } //格式限制 var allowType = new string[] { "image/jpeg", "image/png" }; if (files.Any(b => !allowType.Contains(b.ContentType))) { data.Msg = $"只能上传{string.Join(",", allowType)}格式的文件。"; return Json(data); } //大小限制 if (files.Sum(b => b.Length) >= 1024 * 1024 * 4) { data.Msg = "上传文件的总大小只能在4M以下。"; return Json(data); } //初始化上传多个文件的Bar,存储到缓存中,方便获取上传进度 var listBar = new List<MoBar>(); files.ToList().ForEach(b => { listBar.Add(new MoBar { FileName = b.FileName, Status = 1, CurrBar = 0, TotalBar = b.Length }); }); _cache.Set<List<MoBar>>(cacheKey, listBar); //写入服务器磁盘 foreach (var file in files) { //总大小 var totalSize = file.Length; //初始化每次读取大小 var readSize = 1024L; var bt = new byte[totalSize > readSize ? readSize : totalSize]; //当前已经读取的大小 var currentSize = 0L; var fileName = file.FileName; var path = Path.Combine(@"D:\F\学习\vs2017\netcore\netcore01\WebApp01\wwwroot\myfile", fileName); using (var stream = System.IO.File.Create(path)) { //await file.CopyToAsync(stream); //进度条处理流程 using (var inputStream = file.OpenReadStream()) { //读取上传文件流 while (await inputStream.ReadAsync(bt, 0, bt.Length) > 0) { //当前读取的长度 currentSize += bt.Length; //写入上传流到服务器文件中 await stream.WriteAsync(bt, 0, bt.Length); //获取每次读取的大小 readSize = currentSize + readSize <= totalSize ? readSize : totalSize - currentSize; //重新设置 bt = new byte[readSize]; //设置当前上传的文件进度,并重新缓存到进度缓存中 var bars = _cache.Get<List<MoBar>>(cacheKey); var currBar = bars.Where(b => b.FileName == fileName).SingleOrDefault(); currBar.CurrBar = currentSize; currBar.Status = currentSize >= totalSize ? 2 : 1; _cache.Set<List<MoBar>>(cacheKey, bars); System.Threading.Thread.Sleep(1000 * 1); } } } } data.Msg = "上传完成"; data.Status = 2; } catch (Exception ex) { data.Msg = ex.Message; } return Json(data); }