简体   繁体   English

在 ASP.NET MVC 中的上传文件中使用 TempData

[英]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#我已经实现了在我的项目 MVC asp net c# 中上传文件的形式

My problem:我的问题:

If I try upload the file not image(jpg,gif,png) eg a txt file the return in window popup is如果我尝试上传文件而不是图像(jpg,gif,png),例如 txt 文件,则 window 弹出窗口中的返回是

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

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.发生的情况是,在您向 Controller 发布后,会呈现一个新页面,其中不包括原始上传文件选择。

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.处理此问题的最简单方法是使用一些简单的 Javascript 检查客户端上的文件名,并且仅在其有效时才提交表单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM