使用引导进度条以模态显示上传进度

Posted

技术标签:

【中文标题】使用引导进度条以模态显示上传进度【英文标题】:Display Upload Progress in Modal with Bootstrap Progress Bar 【发布时间】:2015-04-20 03:01:02 【问题描述】:

我正在构建一个 c# MVC 应用程序,它显示一个表单并允许用户上传一些文件。当用户点击提交时,会出现一个带有进度条的模式,设置为 100% 并显示一条消息“请稍候,等等。”

我希望能够捕获上传过程的进度并将其显示在模态的进度条中。

所以经过一些 Google 搜索后,我想出了this solution,但我不确定如何使其适应我目前的情况。

这是我的代码:

索引.cshtml

<h4>Please fill out the form below and select at least one file to upload.</h4>

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new  enctype = "multipart/form-data", id = "upldFrm" ))

    <div class="row">
        <div class="col-md-2">
            <h5>Your Name:</h5>
        </div>
        <div class="col-md-4">
            <input type="text" name="uname" class="form-control" required placeholder="John Smith">
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <h5>Your Email:</h5>
        </div>
        <div class="col-md-4">
            <input type="email" name="email" class="form-control" required placeholder="test@test.com">
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <h5>Your Company:</h5>
        </div>
        <div class="col-md-4">
            <input type="text" name="company" class="form-control" required placeholder="Test Company, Inc">
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <h5>Choose file(s) to upload (Max 500MB):</h5>
        </div>
        <div class="col-md-4">
            <input name="files" type="file" id="files" multiple="multiple" class="form-control" required />
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <h5></h5>
        </div>
        <div class="col-md-4">
            <input id="sbmtBtn" type="submit" name="submit" value="Upload" class="btn btn-primary" data-toggle="modal" data-target="#myModal" />
        </div>
    </div>


<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1>Uploading...</h1>
            </div>
            <div class="modal-body">
                Please wait while we are uploading your files
                <div class="progress">
                    <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $('sbmtBtn').on('click', function ()
    
        $('#upldFrm').submit();
    );
</script>

这是我的控制器

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;

namespace vidup.Controllers

    public class HomeController : Controller
    
        public ActionResult Index()
        

            return View();
        

        [HttpPost]
        public ActionResult Index(List<HttpPostedFileBase> files)
        
            var userName = Request["uname"].ToString();
            var userEmail = Request["email"].ToString();
            var userCompany = Request["company"].ToString();
            ViewBag.Username = userName;
            ViewBag.UserCompany = userCompany;
            ViewBag.UserEmail = userEmail;
            int i = 0;

            var path = Path.Combine(Server.MapPath("~/Uploads"), userCompany, userName, DateTime.Now.ToString("MM-dd-yyyy h-mm-tt"));
            if (!Directory.Exists(path))
            
                DirectoryInfo di = Directory.CreateDirectory(path);
            

            foreach (HttpPostedFileBase item in files)
            
                i++;
                if (item != null && item.ContentLength > 0)
                
                    var fileName = Path.GetFileName(item.FileName);
                    var fullPath = Path.Combine(path, fileName);
                    ViewBag.Message3 = fileName;
                    ViewBag.Message4 = fullPath;
                    try
                    
                        item.SaveAs(fullPath);
                        var fileCount = i + " File(s) uploaded successfully";
                        ViewBag.Message = fileCount;
                    
                    catch (Exception e)
                    
                        ViewBag.Message = e;
                    
                
                else
                
                    ViewBag.Message = "No File selected";
                
            
            return View("Status");
        

        public ActionResult Status()
        
            return View();
        

    

编辑:

我尝试在我提供的帖子中添加代码,但出现错误

Uncaught ReferenceError: formdata is not defined

这就是我现在的视图,谁能指导我为什么会出现这个错误?或者如何解决?

<div class="row">
        <div class="col-md-2">
            <h5>Choose file(s) to upload (Max 500MB):</h5>
        </div>
        <div class="col-md-4">
            <input name="files" type="file" id="files" multiple="multiple" class="form-control" required />
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <h5></h5>
        </div>
        <div class="col-md-4">
            <input id="sbmtBtn" name="submit" value="Upload" class="btn btn-primary" onclick="submitForm()"/>
        </div>
    </div>


<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1>Uploading...</h1>
            </div>
            <div class="modal-body">
                Please wait while we are uploading your files
                <div class="progress">
                    <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function submitForm() 
        $('#myModal').modal('show');
        var file=document.getElementById('files').files[0];
        var formData = new FormData();
        formdata.append("file_name", file);
        ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", progressHandler, false);
        ajax.addEventListener("load", completeHandler, false);
        ajax.open("POST", '@Url.Action("Index","Home")', true)
        ajax.send(formdata);
    

    function progressHandler(event)
        var percent = (event.loaded / event.total) * 100;
        $('.bar').width(percent);
    

    function completeHandler()
        $('#myModal').modal('hide');
        $('.bar').width(100);
    

    //$('sbmtBtn').on('click', function ()
    //
    //    $('#upldFrm').submit();
    //);
</script>

【问题讨论】:

有人可以帮忙吗?或指出我正确的方向? 这是有争议的事情,但进度条实际上只是为了向用户显示 IMO 正在发生的事情。许多人已经不再使用实际进度,而只是显示“加载轮”或类似的东西。有一个准确的进度条和附加值很少。 【参考方案1】:

我使用以下代码来获取进度条,并且仍然让控制器完成上传文件的工作。

在头部我包含了这些脚本

<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/modernizr-2.8.3.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.css" rel="stylesheet" type="text/css" />

然后是表单的正文和脚本。

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions()  HttpMethod = "POST" , new  enctype = "multipart/form-data" ))
    
        <div class="row">
            <div class="col-md-2">
                <h5>Your Name:</h5>
            </div>
            <div class="col-md-4">
                <input type="text" name="uname" class="form-control" required placeholder="John Smith">
            </div>
        </div>
        <div class="row">
            <div class="col-md-2">
                <h5>Your Email:</h5>
            </div>
            <div class="col-md-4">
                <input type="email" name="email" class="form-control" required placeholder="test@test.com">
            </div>
        </div>
        <div class="row">
            <div class="col-md-2">
                <h5>Your Company:</h5>
            </div>
            <div class="col-md-4">
                <input type="text" name="company" class="form-control" required placeholder="Test Company, Inc">
            </div>
        </div>
        <div class="row">
            <div class="col-md-2">
                <h5>Choose file(s) to upload (Max 500MB):</h5>
            </div>
            <div class="col-md-4">
                <input name="files" type="file" id="files" multiple="multiple" class="form-control" required />
            </div>
        </div>
        <div class="row">
            <div class="col-md-2">
                <h5></h5>
            </div>
            <div class="col-md-4">
                <input id="sbmtBtn" type="submit" name="submit" value="Upload" class="btn btn-primary" />
            </div>
        </div>
    

    <br />
    <div class="progress">
        <div class="progress-bar">0%</div>
    </div>

    <div id="status"></div>

    <script>
        (function () 
            var bar = $('.progress-bar');
            var percent = $('.progress-bar');
            var status = $('#status');

            $('form').ajaxForm(
                beforeSend: function () 
                    status.empty();
                    status.html("Please Wait While We Upload Your File(s)");
                    var percentValue = '0%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                ,
                uploadProgress: function (event, position, total, percentComplete) 
                    var percentValue = percentComplete + '%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                ,
                success: function (d) 
                    var percentValue = '100%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                    $('#fu1').val('');
                    status.empty();
                    alert(d);
                ,
                complete: function (xhr) 
                    status.html("You can Upload again or close this page.");
                
            );
        )();
    </script>

【讨论】:

我喜欢格雷哈默先生

以上是关于使用引导进度条以模态显示上传进度的主要内容,如果未能解决你的问题,请参考以下文章

动画进度条以显示网页的进度

快速在 UICollectionView 中显示多个图像上传的进度条

MVC 文件上传的引导进度条

如何为 Windows 7 编写进度条以在任务栏上进行自我更新?

如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条

制作进度条以获取 AFNetworking 3.0 的响应