Pergunta

Tem alguma HTMLHelper para upload de arquivo? Especificamente, estou procurando uma substituição de

<input type="file"/>

Usando asp.net MVC htmlhelper.

Ou, se eu usar

using (Html.BeginForm()) 

Qual é o controle HTML para o upload do arquivo?

Foi útil?

Solução

Arquivo de upload HTML ASP MVC 3.

Modelo: (Observe que o FileExtensionAttribute está disponível no MVCFutures. Ele validará as extensões de arquivo do lado do cliente e do servidor.)

public class ViewModel
{
    [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", 
             ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
    public HttpPostedFileBase File { get; set; }
}

Visualização 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)
}

Ação do controlador:

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

Outras dicas

Você também pode usar:

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

Eu tive a mesma pergunta há um tempo e me deparei com uma das postagens de Scott Hanselman:

Implementando o upload de arquivos HTTP com o ASP.NET MVC, incluindo testes e maquetes

Espero que isto ajude.

Ou você pode fazer isso corretamente:

Na sua classe de extensão 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));
    }

Está linha:

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

Gera um ID exclusivo para o modelo, você sabe em listas e outras coisas. Modelo [0] .Nome etc.

Crie a propriedade correta no modelo:

public HttpPostedFileBase NewFile { get; set; }

Então você precisa garantir que seu formulário envie arquivos:

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

Então aqui está o seu ajudante:

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

Versão aprimorada da resposta de Paulius Zaliduonis:

Para fazer a validação funcionar corretamente, tive que mudar o modelo para:

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

e a visão de:

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

Isso é necessário porque o que o @Serj Sagan escreveu sobre o atributo FileExtension funcionando apenas com strings.

Usar BeginForm, aqui está a maneira de usá -lo:

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

Isso também funciona:

Modelo:

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

Visão:

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

Ação do controlador:

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

Lista de contentTypes

Acho que isso é um pouco hacky, mas resulta nos atributos de validação corretos etc. sendo aplicados

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top