HTMLフォームからのファイルのアップロードを受け取る (ファイルアップロードを受け付けるジェネリック ハンドラーの作成) - ASP.NET

HTMLフォームからのファイルのアップロードを受け取るジェネリック ハンドラーを作成します。

プログラム例

ASP.NETプロジェクトを新規作成します。プロジェクトの種類は[空の ASP.NET Web アプリケーション]

コード

以下のコードを実装します。
form02.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
  Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
  <form method="post" enctype="multipart/form-data" action="GetForm02.ashx">
    <div>File-01<input name="File01" type="file" /></div>
    <div>File-02<input name="File02" type="file" /></div>
    <div>Value-01<input name="Value01" type="text" /></div>
    <input type="submit" value="POST" />
  </form>
</body>
</html>
GetFrom02.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FormAccept
{
  /// <summary>
  /// GetForm02 の概要の説明
  /// </summary>
  public class GetForm02 : IHttpHandler
  {

    public void ProcessRequest(HttpContext context)
    {
      if (context.Request.HttpMethod == "GET") {
        context.Response.ContentType = "text/plain";
        context.Response.Write("OK+");
      }
      else if (context.Request.HttpMethod == "POST") {
        HttpPostedFile file01 = context.Request.Files["File01"];
        HttpPostedFile file02 = context.Request.Files["File02"];
        string value01 = context.Request.Form["value01"];

        string phyPath = context.Server.MapPath("/");

        file01.SaveAs(phyPath + file01.FileName);
        file02.SaveAs(phyPath + file02.FileName);

        context.Response.ContentType = "text/html";
        context.Response.Write("<html>");
        context.Response.Write("<head></head>");
        context.Response.Write("<body>");
        context.Response.Write(string.Format("<p>value01 = {0:s}</p>", value01));
        context.Response.Write("</body>");
        context.Response.Write("</html>");
      }
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}

解説

ジェネリックハンドラへのアクセスがあった場合、リクエストメソッドがGetかPost化を判定します。リクエストメソッドがGetであった場合は今回は利用しないため、"OK"のテキストを出力します。
リクエストメソッドがPOSTであれば、POSTされたファイルの保存処理をします。
public void ProcessRequest(HttpContext context)
{
  if (context.Request.HttpMethod == "GET") {
    context.Response.ContentType = "text/plain";
    context.Response.Write("OK+");
  }
  else if (context.Request.HttpMethod == "POST") {
    HttpPostedFile file01 = context.Request.Files["File01"];
    HttpPostedFile file02 = context.Request.Files["File02"];
    string value01 = context.Request.Form["value01"];

    string phyPath = context.Server.MapPath("/");

    file01.SaveAs(phyPath + file01.FileName);
    file02.SaveAs(phyPath + file02.FileName);

    context.Response.ContentType = "text/html";
    context.Response.Write("<html>");
    context.Response.Write("<head></head>");
    context.Response.Write("<body>");
    context.Response.Write(string.Format("<p>value01 = {0:s}</p>", value01));
    context.Response.Write("</body>");
    context.Response.Write("</html>");
  }
}

下記のコードで指定したパラメーター名のファイルを取得します。戻り値は HttpPostedFile オブジェクトになります。
context.Request.Files["(パラメーター名)"];でパラメーター名のファイルにアクセスできます。
  HttpPostedFile file01 = context.Request.Files["File01"];
  string phyPath = context.Server.MapPath("/");
  file01.SaveAs(phyPath + file01.FileName);


下記のコードでサーバーマシンでの物理パスを取得します。
string phyPath = context.Server.MapPath("/");

HttpPostedFile オブジェクトのSaveAsメソッドを呼び出し、HttpPostedFile オブジェクトのファイルををディスクに保存します。保存場所のパス、ファイル名を第一引数に与えます。
file01.SaveAs(phyPath + file01.FileName);

アプリケーションの実行

アプリケーションを配置し実行します。form02.htmにWebブラウザでアクセスします。下図の画面が表示されます。


[参照]ボタンを押してファイル参照ボックスにファイルを設定します。また、テキスト入力フィールドに値を入力します。入力ができたら[POST]ボタンを押します。


下図の画面が表示されます。テキスト入力フィールドに入力した値が表示されます。


アプリケーションのルートディレクトリを確認します。先ほどファイル参照ボックスに入れたファイル("test1.txt","test2.txt")がアップロードされています。


ファイルの中身も正しくアップロードされています。


フォームからのファイルのアップロードを受け取るジェネリックハンドラーが作成できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-03-21
iPentec all rights reserverd.