3

以下に拡張メソッドがありますが、これを実行すると、foreachInvalidCastExceptionで * と表示されます。

タイプ 'System.String' のオブジェクトをタイプ 'System.Web.HttpPostedFile' にキャストできません。

コード :

public static List<Attachment> GetFiles(this HttpFileCollection collection) {
            if (collection.Count > 0) {
                List<Attachment> items = new List<Attachment>();
                foreach (HttpPostedFile _file in collection) {
                    if (_file.ContentLength > 0)
                        items.Add(new Attachment()
                        {
                            ContentType = _file.ContentType,
                            Name = _file.FileName.LastIndexOf('\\') > 0 ? _file.FileName.Substring(_file.FileName.LastIndexOf('\\') + 1) : _file.FileName,
                            Size = _file.ContentLength / 1024,
                            FileContent = new Binary(new BinaryReader(_file.InputStream).ReadBytes((int)_file.InputStream.Length))
                        });

                    else
                        continue;
                }
                return items;
            } else
                return null;
        }

前もって感謝します。

MSDN のコメント:

クライアントはファイルをエンコードし、multipart/form-data の HTTP Content-Type ヘッダーを持つマルチパート MIME 形式を使用してコンテンツ本文で送信します。ASP.NET は、エンコードされたファイルをコンテンツ本文から HttpFileCollection の個々のメンバーに抽出します。HttpPostedFile クラスのメソッドとプロパティは、各ファイルのコンテンツとプロパティへのアクセスを提供します。

4

4 に答える 4

7

このページのコード サンプルを見ると、コレクションを列挙する方法が示されています。実際、そのまま列挙しようとすると、文字列が取得されます。

http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx

于 2009-12-15T06:54:58.930 に答える
3

HttpFileCollectionコレクション列挙子はキーを返します。HttpPostedFile関連するオブジェクトを検索するには、ループの各反復でキーを使用する必要があります。したがって、ループは次のようにする必要があります。

foreach (string name in collection) {
    HttpPostedFile _file = collection[name];
    // ...rest of your loop code...
}
于 2009-12-15T06:58:12.297 に答える
1

まあ、私は解決策を見つけましたが、それはとてもばかげているように見えますが、うまくいきます。

私は単にこれを変更しましたforeach

foreach (string fileString in collection.AllKeys) {
                    HttpPostedFile _file = collection[fileString];
                    if (_file.ContentLength > 0)

                        items.Add(new Attachment()
                        {
                            ContentType = _file.ContentType,
                            Name = _file.FileName.LastIndexOf('\\') > 0 ? _file.FileName.Substring(_file.FileName.LastIndexOf('\\') + 1) : _file.FileName,
                            Size = _file.ContentLength / 1024,
                            FileContent = new Binary(new BinaryReader(_file.InputStream).ReadBytes((int)_file.InputStream.Length))
                        });

                    else
                        continue;
                }
于 2009-12-15T06:57:57.743 に答える
1
HttpFileCollection hfc = Request.Files;
  for (int i = 0; i < hfc.Count; i++)
  {
     HttpPostedFile hpf = hfc[i];
     if (hpf.ContentLength > 0)
    {
     string _fileSavePath = _DocPhysicalPath  + "_" + hpf.FileName;
    }
  }
于 2013-01-31T13:39:53.257 に答える