2012-02-29 4 views
4

ファイルを保存するコントローラを作成しました。C#とMVC3でHttpFileCollectionBaseの問題を使用して複数のファイルをアップロード

次のコードは、そのコントローラーの一部です:ASPXページに

if (Request.Files.Count != 0) { 
     HttpFileCollectionBase files = Request.Files; 

     foreach (HttpPostedFileBase file in files) { 
      if (file.ContentLength > 0) { 
       if (!file.ContentType.Equals("image/vnd.dwg")) { 
        return RedirectToAction("List"); 
       } 
      } 
     } 
} 

単純です:

<input type="file" name="file" /> 
<input type="file" name="file" /> 
...// many inputs type file 

私は実行するので、それは私が知っている(のようなエラーを返したため、問題がforeachですデバッグモードで、foreach文にブレークポイントを設定します)。

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFileBase'. 

私の間違いは何ですか?

答えて

10

このようにしてみてください。

[HttpPost] 
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files) 
{ 
    if (files != null && files.Count() > 0) 
    { 
     foreach (var uploadedFile in files) 
     { 
      if (uploadedFile.ContentType != "image/vnd.dwg") 
      { 
       return RedirectToAction("List"); 
      } 

      var appData = Server.MapPath("~/app_data"); 
      var filename = Path.Combine(appData, Path.GetFileName(uploadedFile.FileName)); 
      uploadedFile.SaveAs(filename);      
     } 
    } 

    return RedirectToAction("Success"); 
} 

と、ファイル入力がファイル命名されるようにマークアップを変更します。

<input type="file" name="files" /> 
<input type="file" name="files" /> 
...// many inputs type file 
+0

私は上記のコードを試しました(それは私のコードと思われます)が、私は 'foreach'について私の心を変えました。私は今、 'for'ステートメントを使用しています。それはうまくいく。 –

+0

と最後の言及:コントローラの機能にパラメータがありません –

+0

私はこのソリューションを試しましたが、私は値を取得しません! –

2

は、複数のファイルを処理する方法を示しフィル・ハークによってthis postを見てくださいMVCを使用してアップロードします。使用しようとしているオブジェクトはASP.NET Webforms用です。

3
for (int i = 0; i < Request.Files.Count; i++) 
{ 
    var file = Request.Files[i]; 
    // this file's Type is HttpPostedFileBase which is in memory 
} 

HttpRequestBase.Filesインデックスを必要とするので、for代わりにforeachを使用します。

関連する問題