我创建了以下观点,与具有文件上传和提交按钮。
@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" />
}
我也创建了控制器的操作方法,但它给空在一个“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();
}
ü可以尝试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杜阿尔特评论: [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();
}
见像你这样在这里同样的问题,
代码项目文章关于文件上传,
尝试使用(在控制器):
var file = System.Web.HttpContext.Current.Request.Files[0];
创建模型并将其绑定到你的观点,即控制器也将预计有:
控制器:
//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 :)
使用在控制器中的以下内容:
var file = System.Web.HttpContext.Current.Request.Files[0];
使用HttpPost代替的[AcceptVerbs(HttpVerbs.Post)]