3

asp.net mvc 2 でファイルのアップロードに問題があります。コントローラー関数のパラメーターはFormCollection型です。フィールドが多すぎるため、各フィールドをパラメーターとして分離することはできません。フォームに 2 つのアップロード ファイル フィールドがあります。コントローラーでアップロードされたファイルを取得するにはどうすればよいですか?

私はこの方法を試しました:

public ActionResult CreateAgent(FormCollection collection, HttpPostedFileBase personImage)
{
    ...
}

でしたpersonImagenull。:(

またはこの方法:

HttpPostedFileBase img = this.HttpContext.Request.Files[collection["personImage"]];

しかし、そうimgでしnullた。またcollection["personImage"]、選択したファイルの名前(パスなし)であり、にキャストできませんHttpPostedFileBase

すべてのフィールドを 1 ページに入力する必要があることに注意してください。お客様に別ページで画像をアップロードさせるわけにはいきません!

4

2 に答える 2

9

このブログ投稿を読むことから始めます。次に、それをシナリオに適用します。

<form action="/Home/CreateAgent" method="post" enctype="multipart/form-data">

    <input type="file" name="file1" id="file" />
    <input type="file" name="file2" id="file" />

    ... Some other input fields for which we don't care at the moment
        and for which you definetely should create a view model
        instead of using FormCollection in your controller action

    <input type="submit" />
</form>

WebForms 言語に翻訳すると、次のようになります。

<% using (Html.BeginForm("CreateAgent", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="file1" id="file" />
    <input type="file" name="file2" id="file" />

    ... Some other input fields for which we don't care at the moment
        and for which you definetely should create a view model
        instead of using FormCollection in your controller action

    <input type="submit" />
<% } %>

その後:

public ActionResult CreateAgent(
    // TODO: To be replaced by a strongly typed view model as the 
    // ugliness of FormCollection is indescribable
    FormCollection collection, 
    HttpPostedFileBase file1, 
    HttpPostedFileBase file2
)
{
    // use file1 and file2 here which are the names of the corresponding
    // form input fields
}

多くのファイルがある場合はIEnumerable<HttpPostedFileBase>、Haacked の説明に従って使用してください。

備考:

  • this.HttpContext.Request.FilesASP.NET MVC アプリケーションでは絶対に使用しないでください
  • this.HttpContext.Request.Files[collection["personImage"]]ASP.NET MVC アプリケーションでは絶対に使用しないでください。
于 2011-04-11T20:50:30.023 に答える
2

フォームのビューで using ステートメントはどのように見えますか? 次のようになります。

using (Html.BeginForm("CreateAgent", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })
于 2011-04-11T20:50:00.703 に答える