Html helper para
¿Hay un HTMLHelper
para cargar archivos? Específicamente, estoy buscando un reemplazo de
<input type="file"/>
Utilizando ASP.NET MVC HtmlHelper.
O, Si utilizo
using (Html.BeginForm())
¿Cuál es el control HTML para cargar el archivo?
8 answers
HTML Subir archivo ASP MVC 3.
Modelo: (Tenga en cuenta que FileExtensionsAttribute está disponible en MvcFutures. Validará las extensiones de archivo del lado del cliente y del lado del servidor.)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
Vista 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)
}
Acción del Controlador:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-20 11:57:40
También puedes 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>
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-14 19:17:45
Tuve esta misma pregunta hace un tiempo y me encontré con uno de los mensajes de Scott Hanselman:
Implementación de Carga de archivos HTTP con ASP.NET MVC incluyendo Pruebas y Simulaciones
Espero que esto ayude.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 20:53:08
Versión mejorada de la respuesta de Paulius Zaliaduonis:
Para que la validación funcione correctamente tuve que cambiar el Modelo a:
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;
}
}
}
Y la vista a:
@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)
}
Esto es necesario porque lo que @Serj Sagan escribió sobre el atributo FileExtension funciona solo con cadenas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-18 02:14:44
O podrías hacerlo correctamente:
En su clase de extensión 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));
}
Esta línea:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
Genera un id único para el modelo, ya sabes en las listas y esas cosas. modelo[0]. Nombre, etc.
Cree la propiedad correcta en el modelo:
public HttpPostedFileBase NewFile { get; set; }
Luego debe asegurarse de que su formulario enviará archivos:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
Entonces aquí está tu ayudante:
@Html.FileFor(x => x.NewFile)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-04 09:37:05
Para usar BeginForm
, esta es la forma de usarlo:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-28 11:24:03
Esto también funciona:
Modelo:
public class ViewModel
{
public HttpPostedFileBase File{ get; set; }
}
Vista:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
}
Acción del 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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 07:18:46
Esto es un poco pirateado, supongo, pero resulta en que se apliquen los atributos de validación correctos, etc.
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-24 01:09:45