1

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

@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 中创建了操作方法,但它在“uploadFile”处给出了 null

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

4 回答 4

2

你可以Name试试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]

在您的代码后面:

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

看到这里和你一样的问题。,

关于文件上传的代码项目文章。,

于 2013-09-26T05:11:06.513 回答
1

创建一个模型并将其绑定到控制器也期望的视图:

控制器:

    //Model (for instance I've created it inside controller, you can place it in model
    public class uploadFile
    {
        public HttpPostedFileBase file{ get; set; }
    }

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

查看 @model sampleMVCApp.Controllers.HomeController.uploadFile

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

测试解决方案!

HTH :)

于 2013-09-26T04:46:55.410 回答
1

尝试使用(在控制器上):

var file = System.Web.HttpContext.Current.Request.Files[0];
于 2013-09-26T05:05:41.650 回答
1

在控制器中使用以下内容:

var file = System.Web.HttpContext.Current.Request.Files[0];

使用 HttpPost 而不是 [AcceptVerbs(HttpVerbs.Post)]

于 2013-10-15T09:25:14.197 回答