Search code examples
c#asp.net-mvcuploadtempdata

Using TempData in Upload Files in ASP.NET MVC


I have implemented in an form to upload a file in my project MVC asp net c#

My problem:

If I try upload the file not image(jpg,gif,png) e.g. a txt file the return in window popup is

Please upload only image (jpg,gif,png)

but the data form is emptied of the other data already stored.

It's not possible to warn the user that only image files are accepted and keep the data already stored in the form?

How to do resolve this?

My code below

controller

[HttpPost]
public ActionResult Index(PersonModel person, HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        var fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
        var fileExtension = System.IO.Path.GetExtension(file.FileName);

        if (fileExtension.ToString() == ".jpeg" ||
                    fileExtension.ToString() == ".jpg" ||
                    fileExtension.ToString() == ".gif" ||
                    fileExtension.ToString() == ".png")
        {
            fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fileName.Trim() + fileExtension;
            var userfolderpath = System.IO.Path.Combine(Server.MapPath("~/UploadedFiles/"), fileName);
            file.SaveAs(userfolderpath);                    
            TempData["Message"] = "Ok";
            return RedirectToAction("Index");
        }
        else
        {
            TempData["Message"] = "Please upload only image (jpg,gif,png)";
        }
    }
}

View

@if (TempData["Message"] != null)
{
    <script type="text/javascript">
                window.onload = function () {
                    alert("@TempData["Message"].ToString()");
        };
    </script>
}

Solution

  • What's happening is that after your POST to the Controller a new page is rendered which does not include the original upload file selection.

    Easiest way to handle this would be to check the filename on the client using some simple Javascript, and only submit the form if it's valid.

    var fullPath = document.getElementById('upload').value;
    if (fullPath) {
        var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : 
        fullPath.lastIndexOf('/'));
        var filename = fullPath.substring(startIndex);
        if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
        // Check the filename here and then submit the form if valid
        if (!filename.includes(".jpg") && !filename.includes(".gif"))
        {
             // display error
        }
        else
        {
            document.getElementById("myForm").submit();
        }
    }