I am having trouble displaying a successful message after the file has been downloaded.
At first I tried to use ViewBag.Message, and it works well and displays a “Successful” message after the file is uploaded, and this is what I want. But then I can’t find a way to change this message in a few seconds: “Select a file to upload!” So that the user understands that he can now upload a new file.
I tried to implement a javascript function to process a success message. The problem is that a success message is displayed before the file is downloaded, which is not very good, and if its file is very small, the message will only be displayed for a millisecond.
Do you have any suggestions on how I can configure this? I'm not sure if I should try to continue using javascript or viewbag or something else?
What I'm looking for is a success message, which appears about 5 seconds after a successful download, then returns to "Choose file to download 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(); } } }
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>
source share