MVC 4 Razor文件上传

MVC 4 Razor文件上传

我是新的MVC 4,我试图在我的网站实现文件上传控制。我找不到错误,我在我的文件中得到了一个空值。

主计长:

public class UploadController : BaseController
    {
        public ActionResult UploadDocument()
        {
            return View();
        }

       [HttpPost]
       public ActionResult Upload(HttpPostedFileBase file)
       {
           if (file != null && file.ContentLength > 0)
           {
               var fileName = Path.GetFileName(file.FileName);
               var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
               file.SaveAs(path);
           }

           return RedirectToAction("UploadDocument");
        }
    }

意见:

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


aluckdog
浏览 489回答 3
3回答

RISEBY

这个Upload方法的HttpPostedFileBase参数必须具有与file input.因此,只需将输入更改为:<input&nbsp;type="file"&nbsp;name="file"&nbsp;/>此外,您还可以在Request.Files:[HttpPost]public&nbsp;ActionResult&nbsp;Upload(){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(Request.Files.Count&nbsp;>&nbsp;0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;file&nbsp;=&nbsp;Request.Files[0]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(file&nbsp;!=&nbsp;null&nbsp;&&&nbsp;file.ContentLength&nbsp;>&nbsp;0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;fileName&nbsp;=&nbsp;Path.GetFileName(file.FileName); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;path&nbsp;=&nbsp;Path.Combine(Server.MapPath("~/Images/"),&nbsp;fileName); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file.SaveAs(path); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;RedirectToAction("UploadDocument"); &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP