에 대한 HTML 헬퍼
-
08-07-2019 - |
문제
a HTMLHelper
파일 업로드를 위해? 구체적으로, 나는 교체를 찾고 있습니다
<input type="file"/>
asp.net mvc htmlhelper 사용.
또는 내가 사용하는 경우
using (Html.BeginForm())
파일 업로드의 HTML 컨트롤은 무엇입니까?
해결책
HTML 업로드 파일 ASP MVC 3.
모델: (FileExtensionSattribute는 MVCFutures에서 제공됩니다. File Extensions 클라이언트 측 및 서버 측의 유효성을 검사합니다.)
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);
}
}
}
다른 팁
당신은 또한 사용할 수 있습니다 :
@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>
}
나는이 똑같은 질문을 잠시 후에 있었고 Scott Hanselman의 게시물 중 하나를 발견했습니다.
테스트 및 모의를 포함하여 ASP.NET MVC로 HTTP 파일 업로드 구현
도움이 되었기를 바랍니다.
또는 제대로 할 수 있습니다.
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를 생성합니다. 목록과 물건에 알고 있습니다. 모델 [0]. 이름 등
모델에서 올바른 속성을 만듭니다.
public HttpPostedFileBase NewFile { get; set; }
그런 다음 양식이 파일을 보내도록해야합니다.
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
그런 다음 여기에 당신의 도우미가 있습니다.
@Html.FileFor(x => x.NewFile)
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 속성에 대해 쓴 내용이 필요합니다.
사용 BeginForm
, 사용 방법은 다음과 같습니다.
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
이것은 또한 작동합니다 :
모델:
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;
}
이것은 약간 해킹되지만 올바른 유효성 검사 속성 등이 적용됩니다.
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))