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>