4

I am having few problems with displaying a success message after a file has been uploaded.

I first tried with using the ViewBag.Message , and it works good and display the Success message after the file has been uploaded, which is what I want. But then I cant find a way on how to , after a few seconds change that message back to: "Choose a file to upload !" , so that the user understand he can now upload a new file.

I tried to implement a javascript feature to handle the success message instead. The problem with that is that the success message then shows up before the file upload is completed, which is no good, and if its a very small file, the message will only show for a millisecond.

Do you have any suggestion on how I can fine tune this ? Im not sure if I should try work further using javascript or viewbag, or something different ?

What I am looking for is a success message that are display for around 5 seconds after a successful upload, it then changes back to the "Choose a file to upload message" again.

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 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>
4

3 回答 3

4

一些事情,

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

在视图顶部添加:

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

我们可以sM根据模型值来操作 in JS

<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);
于 2013-05-21T11:45:51.537 回答
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

于 2013-05-21T12:00:37.813 回答
-2

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

于 2013-05-21T11:27:44.757 回答