Html-Helfer für
-
08-07-2019 - |
Frage
Gibt es eine HTMLHelper
für Datei-Upload? Genauer gesagt, ich suche für einen Ersatz von
<input type="file"/>
mit ASP.NET MVC Htmlhelper.
Oder Wenn ich
using (Html.BeginForm())
Was ist die HTML-Steuerung für die Datei-Upload?
Lösung
HTML-Datei hochladen ASP MVC 3.
Modell : (.. Beachten Sie, dass FileExtensionsAttribute in MvcFutures verfügbar Es wird Dateierweiterungen Client-Seite und Server-Seite Validierung)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML-Ansicht :
@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 Aktion :
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
Andere Tipps
Sie können auch verwendet werden:
@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>
}
Ich hatte die gleiche Frage eine Weile zurück und kam in einem von Scott Hanselman Beiträgen:
Implementieren von HTTP-Datei-Upload mit ASP.NET MVC einschließlich Tests und Mocks
Hope, das hilft.
Oder Sie könnten es tun, richtig:
In Ihrer Htmlhelper Erweiterungsklasse:
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));
}
Diese Zeile:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
Erzeugt eine ID einzigartig für das Modell, wissen Sie, in Listen und -material. Modell [0] .Name etc.
Erstellendie richtige Eigenschaft im Modell:
public HttpPostedFileBase NewFile { get; set; }
Dann müssen Sie Ihre Formulardateien stellen Sie sicher, senden:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
dann ist hier Ihr Helfer:
@Html.FileFor(x => x.NewFile)
Verbesserte Version von Paulius Zaliaduonis' Antwort:
Um die Validierungsarbeiten zu machen, richtig hatte ich das Modell zu ändern:
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;
}
}
}
und die Aussicht auf:
@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)
}
Dies ist erforderlich, weil das, was @Serj Sagan schrieb über Fileextension Attribut arbeitet nur mit Streichern.
Zur Nutzung BeginForm
, hier ist die Art und Weise, es zu benutzen:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
Dies funktioniert auch:
Modell:
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" })
}
Controller Aktion:
[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;
}
Dies ist ein wenig hacky ich denke, aber es ergibt sich die richtige Validierungsattribute usw. angewendet werden
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))