MVC-4文件上传成功消息

MVC-4 FileUpload success message

本文关键字:成功 消息 文件 MVC-4      更新时间:2023-09-26

我在上传文件后显示成功消息时遇到了一些问题。

我首先尝试使用ViewBag。消息,它工作得很好,并在文件上传后显示成功消息,这就是我想要的。但是,我不知道如何在几秒钟后将该消息更改为:"选择要上传的文件!",以便用户理解他现在可以上传新文件了。

我尝试实现一个javascript特性来处理成功消息。这样做的问题是,成功消息会在文件上传完成之前显示,这是不好的,如果是一个非常小的文件,消息只会显示一毫秒。

你有什么建议,我可以微调这个吗?我不确定我是否应该尝试使用javascript或viewbag进一步工作,或其他不同的东西?

我要找的是一个成功的消息,显示成功上传后约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();
        }
    }
}

FileUpload视图:

@{
    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>

一些事情,

首先,您需要一个模型来表示成功上传,我们可以在您的实例中使用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);

您可以这样做:

$('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的小库。

也许你可以在它的成功上使用alert() ?这不是最优雅的解决方案,但听起来已经足够了。否则,您应该查看JQuery