[asp.net-mvc] <input type =“file”/>에 대한 HTML 도우미

거기가 HTMLHelper파일 업로드? 특히, 나는 대체를 찾고 있습니다

<input type="file"/>

ASP.NET MVC HTMLHelper를 사용합니다.

또는 내가 사용하는 경우

using (Html.BeginForm()) 

파일 업로드를위한 HTML 컨트롤은 무엇입니까?



답변

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


답변

다음을 사용할 수도 있습니다.

@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 Extension 클래스에서 :

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

contentTypes 목록