MVC-4 FileUpload success message

2019-05-09 02:53发布

问题:

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>

回答1:

Few things,

First, you need a Model to indicate a successful upload, we can just use a bool in your instance to indicate it.

Add this at the top of your view:

@model bool

Then you can do (keeping your view as is):

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

We can manipulate the sM in JS dependent upon the model value

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

Then in your else statement in your action method, just make sure you return true on success, otherwise false. Like so

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);


回答2:

You could do the following:

$('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
        });
    }
});

However it will only work in modern browsers. You could use Modernizr to detect this. For example, if you wrap the code within the form's submit event handler with the following, it will fall back to a regular submit if it is not supported.

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

This also supports progress indication. Simply put a progress tag within the form.

The above code simply alerts the the user when the upload is complete. I use a nice little library called toastr instead.



回答3:

Perhaps you could just use alert() on it's success? Not the most elegant solution but it sounds like it may suffice. Otherwise, you should look into JQuery