<input type="file" /> 的 Html 辅助工具

135

是否有用于文件上传的 HTMLHelper?具体而言,我正在寻找一个替代品。

<input type="file"/>
使用ASP.NET MVC HTMLHelper。
或者,如果我使用

using (Html.BeginForm()) 
8个回答

224

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

@PauliusZaliaduonis 在 Microsoft.Web.Mvc.FileExtensions 这一行中,MVC 下划线是红色的。我该如何修复? - Pomster
1
请注意,FileExtensionsAttribute在MvcFutures中可用(自MVC3起)。 您可以从此处使用源代码:[Sources](http://code.google.com/p/dotnetwise-utiltities/source/browse/trunk/DotNetWise.Utilities/System.ComponentModel.DataAnnotations/FileExtensionsAttribute.cs?spec=svn15&r=15)或者它也可以在.NET Framework 4.5中使用,请参阅[MSDN文档](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.fileextensionsattribute.aspx) - Paulius Zaliaduonis
1
不幸的是,FileExtension属性似乎不能与HttpPostedFileBase类型的属性一起使用,而只能使用字符串。至少它从未接受pdf作为有效的扩展名。 - Serj Sagan
这将添加一个 value 属性 (value=""),它不符合有效的 HTML5 标准。在文件和图片输入类型上,value 是无效的。我没有看到任何删除 value 属性的方法。它似乎是硬编码的。 - Dan Friedman
@SerjSagan 你可以创建一个自定义属性来处理 HttpPostedFileBase 的文件扩展名。请参考这个 stackoverflow 答案 - skeletank
显示剩余4条评论

21

您也可以使用:

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

10
你可以正常地进行操作:
在你的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)

这个解决方案更加美观,而且让我保持与@Html助手方法的一致性。 - Yahfoufi

8

谢谢,但是我特别想要使用(Html.BeginForm())的实现方式,而不是其他变体。 - Graviton

4

Paulius Zaliaduonis的回答有所改进:

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

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属性仅适用于字符串的内容。


你能不能把这个答案合并到 Paulius 的回答中? - Graviton

2

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

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

2
你先提到如何生成一个输入元素,现在又谈论如何生成一个表单元素?这真的是你的答案吗? - pupeno

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

内容类型列表


-2

我觉得这有点取巧,但它确保了正确的验证属性等被应用。

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接