MVC 4剃刀文件上传 [英] MVC 4 Razor File Upload
本文介绍了MVC 4剃刀文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的MVC 4,我想实现文件上传控制
我的网站。我无法找到我犯错误得到一个空
在我的档案价值。
控制器:
公共类UploadController:BaseController
{
公众的ActionResult UploadDocument()
{
返回查看();
} [HttpPost]
公众的ActionResult上传(HttpPostedFileBase文件)
{
如果(文件= NULL&放大器;!&安培; file.ContentLength大于0)
{
变种文件名= Path.GetFileName(file.FileName);
VAR路径= Path.Combine(使用Server.Mappath(〜/图片/),文件名);
file.SaveAs(路径);
} 返回RedirectToAction(UploadDocument);
}
}
查看:
@using(Html.BeginForm(上传,上传,FormMethod.Post,新{ENCTYPE =的multipart / form-data的}))
{
<输入类型=文件名称=文件上传/>
<输入类型=提交名称=提交ID =提交值=上传/>
}
解决方案
的上传
方法的 HttpPostedFileBase
参数必须具有在相同的名称在文件输入
。
因此,只要输入更改为这样的:
<输入类型=文件名称=文件/>
此外,你会发现在文件 Request.Files
:
[HttpPost]
公众的ActionResult上传()
{
如果(Request.Files.Count大于0)
{
var文件= Request.Files [0]; 如果(文件= NULL&放大器;!&安培; file.ContentLength大于0)
{
变种文件名= Path.GetFileName(file.FileName);
VAR路径= Path.Combine(使用Server.Mappath(〜/图片/),文件名);
file.SaveAs(路径);
}
} 返回RedirectToAction(UploadDocument);
}
I am new to MVC 4 and I am trying to implement File Upload Control in my website. I am not able to find the mistake.I am getting a null value in my file.
Controller:
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");
}
}
View:
@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" />
}
解决方案
The Upload
method's HttpPostedFileBase
parameter must have the same name as the the file input
.
So just change the input to this:
<input type="file" name="file" />
Also, you could find the files in Request.Files
:
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
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");
}
这篇关于MVC 4剃刀文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文