我创建了以下视图,其中包含文件上传和提交按钮。
@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();
}
答案 0 :(得分: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();
}
答案 1 :(得分: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:)
答案 2 :(得分:1)
尝试使用(在控制器上):
var file = System.Web.HttpContext.Current.Request.Files[0];
答案 3 :(得分:1)
在控制器中使用以下内容:
var file = System.Web.HttpContext.Current.Request.Files[0];
使用HttpPost代替[AcceptVerbs(HttpVerbs.Post)]