2011-01-24 16 views
91

私は動作するフォームのアップロードがありますが、データベースのモデル情報を渡して別の名前のファイルを保存したいとします。MVC 3ファイルのアップロードとモデルのバインド

は、ここに私のかみそり図である:

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 0) 
    { 
     var fileName = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), 
         containers.ContainerNo); 
     file.SaveAs(path); 
    } 

    return RedirectToAction("Index"); 
} 

モデル情報は、コントローラに渡されていません。

@model CertispecWeb.Models.Container 

@{ 
    ViewBag.Title = "AddDocuments"; 
} 

<h2>AddDocuments</h2> 

@Model.ContainerNo 

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, 
      new { enctype = "multipart/form-data" })) 
{ 
    <input type='file' name='file' id='file' /> 
    <input type="submit" value="submit" /> 
} 

はここに私のコントローラです。私はモデルを更新する必要があるかもしれないことを読んだが、どうすればよいだろうか?

+2

はhttp://stackoverflow.com/questions/9411563/asp-net-mvc3-razor-file-upload-gives-zeroを参照してください。 -as-file-count関連する問題 – Lijo

答えて

124

あなたのフォームにはファイル以外の入力タグは含まれていないので、コントローラのアクションでは、アップロードされたファイル以外のものを得ることはできません(すべてサーバーに送信されます)。これを実現する1つの方法は、モデルのIDを含む隠しタグを含めることです。これは、あなたが投稿しているコントローラアクション内のデータストアからデータを取得することを可能にします(ユーザーがモデルを変更することは想定されていません。単に)ファイルを添付:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.HiddenFor(x => x.Id) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

してからコントローラのアクションで:

[HttpPost] 
public ActionResult Uploadfile(int id, HttpPostedFileBase file) 
{ 
    Containers containers = Repository.GetContainers(id); 
    ... 
} 

一方、ユーザーがこのモデルを変更できるように望んでいたならば、あなたは正しいを含める必要があります。サーバーに送信するモデルの各フィールドの入力フィールド:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.TextBoxFor(x => x.Prop1) 
    @Html.TextBoxFor(x => x.Prop2) 
    @Html.TextBoxFor(x => x.Prop3) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

、その後、あなたは、デフォルトのモデルバインダーが要求からこのモデルを再構築があります:あなたは、常にイメージが自分の行動への投稿はありません場合は

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    ... 
} 
+4

ありがとう、素晴らしい作品です。 Francis – Francis

+1

'file'を' null'とし、 'Request.Files.Count'も0です。' form'が 'AjaxForm'で' routeValues'もあれば違いはありますか? – bjan

6

は、あなたがこのような何かを行うことができます。

[HttpPost] 
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{ 
    //do container stuff 

    if (Request.Files != null) 
    { 
     foreach (string requestFile in Request.Files) 
     { 
      HttpPostedFileBase file = Request.Files[requestFile]; 
      if (file.ContentLength > 0) 
      { 
       string fileName = Path.GetFileName(file.FileName); 
       string directory = Server.MapPath("~/App_Data/uploads/"); 
       if (!Directory.Exists(directory)) 
       { 
        Directory.CreateDirectory(directory); 
       } 
       string path = Path.Combine(directory, fileName); 
       file.SaveAs(path); 
      } 
     } 
    } 

} 
8

モデル

を解決しましたコントローラアクションからのパラメータの

public class BookController : Controller 
{ 
    [HttpPost] 
    public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload) 
    { 
     throw new NotImplementedException(); 
    } 
} 

とビュー

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{  
    @Html.EditorFor(m => m) 

    <input type="file" name="fileUpload[0]" /><br />  
    <input type="file" name="fileUpload[1]" /><br />  
    <input type="file" name="fileUpload[2]" /><br />  

    <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" /> 
} 

ノートのタイトルを入力要素 IEnumerable<HttpPostedFileBase> fileUploadの名前と一致する必要があります

コントローラ - >name="fileUpload[0]"

fileUpload

+2

このソリューションは、私が複数のファイルで見つけた唯一の解決策です。コードを共有していただきありがとうございます。 –

1
と一致する必要があります

複数のファイルの場合。入力の新しい "複数" 属性の点に注意してください。

フォーム:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"})) 
{ 
    <label for="files">Filename:</label> 
    <input type="file" name="files" multiple="true" id="files" /> 
    <input type="submit" /> 
} 

コントローラー:以下のURLから

[HttpPost] 
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files) 
{ 
    return View(); 
} 
1

第一ダウンロードjquery.form.jsファイル

http://plugins.jquery.com/form/

書き込みCSHTMLでのコードの下に電子

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" })) 
{ 
    <div id="uploadTemplate"> 

     <input type="text" value="Asif" id="txtname" name="txtName" /> 


     <div id="dvAddTemplate"> 
      Add Template 
      <br /> 
      <input type="file" name="file" id="file" tabindex="2" /> 
      <br /> 
      <input type="submit" value="Submit" /> 
      <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" /> 
     </div> 

     <div id="TemplateTree" style="overflow-x: auto;"></div> 
    </div> 

    <div id="progressBarDiv" style="display: none;"> 
     <img id="loading-image" src="~/Images/progress-loader.gif" /> 
    </div> 

} 


<script type="text/javascript"> 

    $(document).ready(function() { 
     debugger; 
     alert('sample'); 
     var status = $('#status'); 
     $('#frmTemplateUpload').ajaxForm({ 
      beforeSend: function() { 
       if ($("#file").val() != "") { 
        //$("#uploadTemplate").hide(); 
        $("#btnAction").hide(); 
        $("#progressBarDiv").show(); 
        //progress_run_id = setInterval(progress, 300); 
       } 
       status.empty(); 
      }, 
      success: function() { 
       showTemplateManager(); 
      }, 
      complete: function (xhr) { 
       if ($("#file").val() != "") { 
        var millisecondsToWait = 500; 
        setTimeout(function() { 
         //clearInterval(progress_run_id); 
         $("#uploadTemplate").show(); 
         $("#btnAction").show(); 
         $("#progressBarDiv").hide(); 
        }, millisecondsToWait); 
       } 
       status.html(xhr.responseText); 
      } 
     }); 

    }); 


</script> 

対処方法: -

public ActionResult Index() 
     { 
      ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

      return View(); 
     } 

public void Upload(HttpPostedFileBase file, string txtname) 
     { 

      try 
      { 
       string attachmentFilePath = file.FileName; 
       string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1); 

      } 
      catch (Exception ex) 
      { 

      } 
     } 
関連する問題