MVC-4文件上传成功消息

4
我在上传文件后无法成功显示成功信息。我最初尝试使用ViewBag.Message,它可以在文件上传后正常工作并显示“成功”消息,这正是我想要的。但是,我找不到一种方法来在几秒钟后将该消息更改回“选择要上传的文件!”,以便用户了解他现在可以上传新文件。
然后,我尝试使用JavaScript功能来处理成功消息。问题在于,成功消息会在文件上传完成之前显示出来,这不好,如果文件非常小,则消息仅会显示一毫秒。
您有任何建议可以帮助我微调这个问题吗?我不确定是否应尝试进一步使用JavaScript或视图包或其他东西?
我正在寻找的是一个成功消息,在成功上传后显示约5秒钟,然后再次更改为“选择要上传的文件”消息。 https://github.com/xoxotw/mvc_fileUploader
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace Mvc_fileUploader.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //ViewBag.Message = "Choose a file to upload !";
            return View("FileUpload");
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase fileToUpload)
        {

            if (ModelState.IsValid)
            {
                if (fileToUpload != null && fileToUpload.ContentLength > (1024 * 1024 * 2000))  // 1MB limit
                {
                    ModelState.AddModelError("fileToUpload", "Your file is to large. Maximum size allowed is 1MB !");
                }

                else
                {
                    string fileName = Path.GetFileName(fileToUpload.FileName);
                    string directory = Server.MapPath("~/fileUploads/");

                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    string path = Path.Combine(directory, fileName);
                    fileToUpload.SaveAs(path);

                    ModelState.Clear();
                    //ViewBag.Message = "File uploaded successfully !";

                 }
            }

            return View("FileUpload");

        }



        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

文件上传视图:

@{
    ViewBag.Title = "FileUpload";
}

<h2>FileUpload</h2>

<h3>Upload a File:</h3>


@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{ 
    @Html.ValidationSummary();
    <input type="file" name="fileToUpload" /><br />
    <input type="submit" onclick="successMessage()" name="Submit" value="upload" />  
    //@ViewBag.Message
    <span id="sM">Choose a file to upload !</span>
}


<script>
    function successMessage()
    {
        x = document.getElementById("sM");
        x.innerHTML = "File upload successful !";
    }
</script>
3个回答

4

首先,您需要一个模型来指示上传成功,我们可以在您的实例中使用bool来表示它。

将以下代码添加到您的视图顶部:

@model bool

然后你可以这样做(保持你的视图不变):
@{
    ViewBag.Title = "FileUpload";
}

<h2>FileUpload</h2>

<h3>Upload a File:</h3>

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{ 
    @Html.ValidationSummary();
    <input type="file" name="fileToUpload" /><br />
    <input type="submit" onclick="successMessage()" name="Submit" value="upload" />  

    <span id="sM">Choose a file to upload !</span>
}

我们可以根据模型值在 JS 中操作 sM
<script>

    @if(Model)
    {
        var x = document.getElementById("sM");
        x.innerHTML = "File upload successful !";
        setTimeout("revertSuccessMessage()", 5000);
    }

    function revertSuccessMessage()
    {
        var x = document.getElementById("sM");
        x.innerHTML = "Choose a file to upload !";
    }
</script>

然后在您的操作方法中的else语句中,确保在成功时返回true,否则返回false。就像这样:

else
{
    string fileName = Path.GetFileName(fileToUpload.FileName);
    string directory = Server.MapPath("~/fileUploads/");

    if (!Directory.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }

    string path = Path.Combine(directory, fileName);
    fileToUpload.SaveAs(path);

    ModelState.Clear();

    return View("FileUpload", true);
}

return View("FileUpload", false);

0
你可以这样做:
$('form').submit(function(e) {
    var form = $(this);

    if (form.valid()) {
        e.preventDefault();

        $.ajax(form.attr('action'), {
            data: new FormData(form[0]),
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                var progress = $('progress', form);

                if (myXhr.upload && progress.length > 0) {
                    progress.show();

                    myXhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable)
                            progress.attr({ value: e.loaded, max: e.total });
                    }, false);
                }

                return myXhr;
            },
            success: function(e) {
                alert('Upload complete!');
            },
            // Options to tell JQuery not to process data or worry about content-type
            contentType: false,
            processData: false
        });
    }
});

然而,它只能在现代浏览器中运行。您可以使用Modernizr来检测这一点。例如,如果您将代码包装在表单的提交事件处理程序中,并使用以下代码,如果不支持,则会回退到常规提交。

if (Modernizr.input.multiple) {
    ...
}

这也支持进度指示。只需在表单中放置一个进度标签即可。
上述代码只是在上传完成时向用户发出警报。我使用一个很好的小库,叫做toastr

-2
也许你可以在成功时使用alert()?虽然不是最优雅的解决方案,但听起来可能已经足够了。否则,你应该研究一下JQuery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接