asp.net-mvc <input type="file" /> 的 HTML 助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/304617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html helper for <input type="file" />
提问by Graviton
Is there a HTMLHelperfor file upload? Specifically, I am looking for a replace of
有HTMLHelper文件上传吗?具体来说,我正在寻找替代品
<input type="file"/>
using ASP.NET MVC HTMLHelper.
使用 ASP.NET MVC HTMLHelper。
Or, If I use
或者,如果我使用
using (Html.BeginForm())
What is the HTML control for the file upload?
文件上传的HTML控件是什么?
回答by Paulius Zaliaduonis
HTML Upload File ASP MVC 3.
HTML 上传文件 ASP MVC 3.
Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)
模型:(请注意 FileExtensionsAttribute 在 MvcFutures 中可用。它将验证文件扩展名客户端和服务器端。)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML View:
HTML 视图:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
Controller action:
控制器动作:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
回答by balexandre
You can also use:
您还可以使用:
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload" size="23" />
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
回答by Dan Atkinson
I had this same question a while back and came across one of Scott Hanselman's posts:
不久前我遇到了同样的问题,并遇到了 Scott Hanselman 的一篇文章:
Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
使用 ASP.NET MVC 实现 HTTP 文件上传,包括测试和模拟
Hope this helps.
希望这可以帮助。
回答by Tod
Or you could do it properly:
或者你可以正确地做到这一点:
In your HtmlHelper Extension class:
在您的 HtmlHelper 扩展类中:
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
return helper.FileFor(expression, null);
}
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var builder = new TagBuilder("input");
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
builder.GenerateId(id);
builder.MergeAttribute("name", id);
builder.MergeAttribute("type", "file");
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
This line:
这一行:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.
生成模型唯一的 id,您在列表和其他东西中知道。模型[0].名称等
Create the correct property in the model:
在模型中创建正确的属性:
public HttpPostedFileBase NewFile { get; set; }
Then you need to make sure your form will send files:
然后你需要确保你的表单会发送文件:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
Then here's your helper:
那么这是你的帮手:
@Html.FileFor(x => x.NewFile)
回答by BornToCode
Improved version of Paulius Zaliaduonis' answer:
Paulius Zaliaduonis 回答的改进版本:
In order to make the validation work properly I had to change the Model to:
为了使验证正常工作,我必须将模型更改为:
public class ViewModel
{
public HttpPostedFileBase File { get; set; }
[Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
public string FileName
{
get
{
if (File != null)
return File.FileName;
else
return String.Empty;
}
}
}
and the view to:
并认为:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.FileName)
}
This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.
这是必需的,因为@Serj Sagan 写的关于 FileExtension 属性的内容仅适用于字符串。
回答by Graviton
To use BeginForm, here's the way to use it:
要使用BeginForm,这是使用它的方法:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
回答by Eyal
This also works:
这也有效:
Model:
模型:
public class ViewModel
{
public HttpPostedFileBase File{ get; set; }
}
View:
看法:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
}
Controller action:
控制器动作:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
var postedFile = Request.Files["File"];
// now you can get and validate the file type:
var isFileSupported= IsFileSupported(postedFile);
}
}
public bool IsFileSupported(HttpPostedFileBase file)
{
var isSupported = false;
switch (file.ContentType)
{
case ("image/gif"):
isSupported = true;
break;
case ("image/jpeg"):
isSupported = true;
break;
case ("image/png"):
isSupported = true;
break;
case ("audio/mp3"):
isSupported = true;
break;
case ("audio/wav"):
isSupported = true;
break;
}
return isSupported;
}
回答by Luke Schafer
This is a little hacky I guess, but it results in the correct validation attributes etc being applied
我猜这有点棘手,但它会导致应用正确的验证属性等
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))

