c# 大文件上传 前端ajax显示进度条

记录下 今天的研究笔记。

前端页面

@{
    ViewBag.Title = "Home Page";
}
<style type="text/css">
        .main {
            padding: 20px 28px;
            margin: 0 auto;
        }

        .progressNum {
            text-align: center;
            font-size: 12px;
            font-family: 'microsoft yahei';
            color: #000;
        }
        .progress {
            height: 22px;
            margin-bottom: 22px;
            overflow: hidden;
            background-color: #e4eaec;
            border-radius: 3px;
            -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
            box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
        }
        .progress-bar {
            float: left;
            width: 0;
            height: 100%;
            font-size: 12px;
            line-height: 22px;
            color: #fff;
            text-align: center;
            background-color: #62a8ea;
            -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
            box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
            -webkit-transition: width .6s ease;
            -o-transition: width .6s ease;
            transition: width .6s ease;
        }
        .progress-bar-striped, .progress-striped .progress-bar {
            background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
            background-image: -o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
            background-image: linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
            -webkit-background-size: 40px 40px;
            background-size: 40px 40px;
        }
        .progress-bar.active, .progress.active .progress-bar {
            -webkit-animation: progress-bar-stripes 2s linear infinite;
            -o-animation: progress-bar-stripes 2s linear infinite;
            animation: progress-bar-stripes 2s linear infinite;
        }
</style>
<div class="jumbotron">
    <input type="file" id="upload" onchange="validate(this)" />
    <div id="process">
    </div>
   
    <br />
    <div id="v"></div>
</div>
<script>
 

    function validate(t) {
        //debugger;
        var objt = $('#upload');

        var obj = objt[0].files[0];
        if (obj == undefined) {
            layer.msg("请选择上传图片!", { icon: 2 });
            return;
        }
        var formData = new FormData();
        formData.append("img", obj);
        $.ajax({
            type: "post",
            url: "/Home/UploadImage",
            data: formData,
            processData: false, // 使数据不做处理
            contentType: false, // 不要设置Content-Type请求头
            xhr: function () { //获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) { //检查upload属性是否存在
                    //绑定progress事件的回调函数
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr; //xhr对象返回给jQuery使用
            },
            success: function (data) {
                console.log(data);
                if (data.msg != "") {
                    $("#v").html("");
                } else {
                    alert(data.msg);
                }
            }
        })
    }

     function progressHandlingFunction(e) {
        var curr = e.loaded;
        var total = e.total;
        process = curr / total * 100;
        process = process.toFixed(2);
        var str = '
\
\
+ process+'%" role="progressbar">\
\
\ 完成进度:'+ process+'% \
'
; $("#process").html('').html(str); if (process >= 100) { setTimeout(function () { $("#process").html(''); }, 2300) } } </script>

后端代码

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace upload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult UploadImage()
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            var postFile = files[0];
            if (postFile.ContentLength == 0)
            {
                return Json(new { msg="上传文件为空"},JsonRequestBehavior.AllowGet);
            }

            try
            {
                string format = SaveFile(postFile);
                return Json(new { msg = "上传成功",filepath= format }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { msg = "上传失败" }, JsonRequestBehavior.AllowGet);
            }
        }

     
        private string SaveFile(HttpPostedFile file)
        {
            string path = @"H:\uploadBig\upload\upload\Files";
            string retMsg =  DateTime.Now.ToString("yyyyMMddHHmmss") + "." + file.FileName.Split('.').Last();
            FileStream fs = new FileStream(path + "\\"+retMsg, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            BinaryReader br = new BinaryReader(file.InputStream);
            int totalCount = file.ContentLength;
            byte[] bufferByte;
            int size = 102400;
            int readCount = 0;//单次读取的字节数
           // int readCount = (int)Math.Ceiling((double)(fileLength / size )) 第二种分块方式
            while (readCount < totalCount)
            {
                bufferByte = new byte[size];
                bufferByte = br.ReadBytes(size);
                readCount += size;
                bw.Write(bufferByte, 0, bufferByte.Length);//写入字节到文件流
                bw.Flush();
                //写入缓存 用于拓展 可注释
                HttpContext.Cache.Insert("Admin_UploadSpeed_", (readCount * 100.0 / totalCount).ToString("0.00"), null, DateTime.Now.AddSeconds(1), System.Web.Caching.Cache.NoSlidingExpiration);
                //后台监听写入进度 可注释
                System.IO.File.AppendAllText(path + "/1.txt", (readCount * 1.0 / totalCount).ToString("0.00")+System.Environment.NewLine);
            }
            bw.Close();
            bw.Dispose();

            return retMsg;
        }
    }
}

关于大文件上传的设置 需要开启:
1.修改IIS的applicationhost.config
文件位置: %windir%\system32\inetsrv\config\applicationhost.config
ctrl+F 找到 requestFiltering 节点,该节点下默认没有requestLimits 元素。
为这个节点添加如下元素:(上传的大小将改为2G)

<requestLimits maxAllowedContentLength="2147483647" />

2.发布后需要在网站目录下修改web.config中添加如下内容:
在web.config 的configuration节点下加上

<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483647"/>
</requestFiltering>
</security>
</system.webServer>

效果粗糙了些:
c# 大文件上传 前端ajax显示进度条_第1张图片
c# 大文件上传 前端ajax显示进度条_第2张图片

c# 大文件上传 前端ajax显示进度条_第3张图片

拓展处 后期通过分块读取的思想
1.做成多线程处理(提高服务器端的接收速度)
2.分块读写 做成 redis根据用户存储 写分块文件名 下次传同文件可实现断点续传。

今天的笔记就先做到这里。。。

你可能感兴趣的:(c#)