MVC4 Razor中文件上传中的Null异常 [英] Null Exception in File Uploading in MVC4 Razor

查看:73
本文介绍了MVC4 Razor中文件上传中的Null异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下视图,并带有文件上传和提交按钮.

I have created the following view, with having file upload and submit button.

@using (Html.BeginForm("FileUpload", "Home",
                    FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input name="uploadFile" type="file" />
    <input type="submit" value="Upload File" id="btnSubmit" />
}

我也在Controller中创建了action方法,但它在"uploadFile"处提供了空值

I have also created the action method in Controller but it gives the null at the "uploadFile"

[HttpPost)]
        public ActionResult FileUpload(HttpPostedFileBase uploadFile)
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                                               Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
            }
            return View();
        }

推荐答案

您可以尝试与uploadFile

在您的页面中:

@using (Html.BeginForm("FileUpload", "Home",
                    FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input id="uploadFile" name="uploadFile" type="file" />
    <input type="submit" value="Upload File" id="btnSubmit" />
}

根据@Willian Duarte的评论:[HttpPost]

As per @Willian Duarte comment : [HttpPost]

在您后面的代码中:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile) // OR IEnumerable<HttpPostedFileBase> uploadFile
{
    //For checking purpose 
     HttpPostedFileBase File = Request.Files["uploadFile"];

    if (File != null)
    {
        //If this is True, then its Working.,
    }

    if (uploadFile.ContentLength > 0)
    {
        string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                                       Path.GetFileName(uploadFile.FileName));
        uploadFile.SaveAs(filePath);
    }
    return View();
}

请参见此处与您相同的问题.

有关文件上传的代码项目文章.

这篇关于MVC4 Razor中文件上传中的Null异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆