<input type =“file”/>的Html帮助器

时间:2008-11-20 08:12:50

标签: asp.net-mvc razor file-upload upload

文件上传是否有HTMLHelper?具体来说,我正在寻找

的替代品
<input type="file"/>

使用ASP.NET MVC HTMLHelper。

或者,如果我使用

using (Html.BeginForm()) 

文件上传的HTML控件是什么?

8 个答案:

答案 0 :(得分:198)

HTML上传文件ASP MVC 3。

模型 :( 请注意,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查看

@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)
}

控制器操作

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Use your file here
        using (MemoryStream memoryStream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(memoryStream);
        }
    }
}

答案 1 :(得分:18)

您也可以使用:

@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> 
}

答案 2 :(得分:7)

我有一段时间没有同样的问题,并且遇到了Scott Hanselman的一个帖子:

Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks

希望这有帮助。

答案 3 :(得分:5)

或者你可以正确地做到:

在你的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));
    }

这一行:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

生成模型独有的ID,您可以在列表和内容中知道。 model [0] .Name等。

在模型中创建正确的属性:

public HttpPostedFileBase NewFile { get; set; }

然后你需要确保你的表单会发送文件:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

然后,这是你的帮手:

@Html.FileFor(x => x.NewFile)

答案 4 :(得分:4)

改良版的Paulius Zaliaduonis&#39;回答:

为了使验证工作正常,我必须将模型更改为:

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;
            }
        }
}

和观点:

@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)
}

这是必需的,因为@Serj Sagan写的关于FileExtension属性只能使用字符串。

答案 5 :(得分:2)

要使用BeginForm,以下是使用它的方法:

 using(Html.BeginForm("uploadfiles", 
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})

答案 6 :(得分:0)

这也有效:

<强>型号:

public class ViewModel
{         
    public HttpPostedFileBase File{ get; set; }
}

查看:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })       
}

控制器操作:

[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;
            }

List of contentTypes

答案 7 :(得分:-1)

我猜这有点像hacky,但它会导致正确的验证属性等被应用

_mouseUp()