9

ASP.NET MVC Web サイトを持っています。ユーザーが画像ファイルを含むいくつかのフィールドを入力する必要があるページが必要です。

MVC を使用してファイルをアップロードする方法については、非常に多くの参考文献を見つけることができました。ただし、他のフィールドを含むフォームの一部としてファイルをアップロードすることはありません。

理想的には、フィールドとファイルは単一のコントローラーに送信されます。任意のヒント?

4

2 に答える 2

11

サードパーティのライブラリを使用していない場合は、次を試してください。

モデル

public class Strategy 
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public byte[] File { get; set; }

    }

意見

 @model TEST.Model.Strategy
 @using (Html.BeginForm("Add", "Strategy", FormMethod.Post, new { @id = "frmStrategy", enctype = "multipart/form-data" }))
        {
            @Html.TextBoxFor(x => x.Name)
            <input id="templateFile" name="templateFile" type="file"  />
            @Html.HiddenFor(x => x.ID)

        }

コントローラ

[HttpPost]
        public ActionResult Add(Strategy model, HttpPostedFileBase templateFile)
        {


            if (templateFile != null && templateFile.ContentLength > 0)
            {
                try
                {
                    var fname = Path.GetFileName(templateFile.FileName);
                    using (MemoryStream ms = new MemoryStream())
                    {
                      templateFile.InputStream.CopyTo(ms);
                      byte[] array = ms.GetBuffer();
                      model.File = array;
                    }
                    ...
于 2013-06-15T22:02:05.910 に答える