質問

ファイルのアップロード用の 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> 
}

私はしばらく前に同じ質問をしましたが、スコット・ヘンゼルマンの投稿の1つに出会いました:

テストとモックを含む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を生成します。これはリストなどで知っています。 model [0] .Nameなど。

モデルに正しいプロパティを作成します:

public HttpPostedFileBase NewFile { get; set; }

次に、フォームがファイルを送信することを確認する必要があります:

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

次に、あなたのヘルパーがいます:

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

パウリウス・ザリアドゥオニスの答えの改良版:

検証を適切に機能させるには、モデルを次のように変更する必要がありました。

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のリスト

これは少しおかしいと思いますが、正しい検証属性などが適用されます

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top