ファイルのダウンロード機能を実装する方法

download.gifサンプル コードのダウンロード (PHPtips_Download.msi, 245 KB)

※このサンプルをお使いいただくためには、Visual Studio 2005 が必要です。

ファイルのダウンロード機能は、HTTP ヘッダを指定してデータを出力することで実装できます。
PHP では、header 関数を使って、HTTP ヘッダを指定し、readfile 関数にダウンロードさせたいファイルを指定して出力します。従来の ASP では、Response オブジェクトの AddHeader メソッドで HTTP ヘッダを指定し、Response オブジェクトの WriteFile メソッドにダウンロードさせたいファイルを指定して出力します。 ASP.NET 2.0 では、HttpResponse クラスの AddHeader メソッドで HTTP ヘッダを指定し、HttpResponse クラスの WriteFile メソッドにダウンロードさせたいファイルを指定して出力します。では、実際にファイルをダウンロードするページを作ってみましょう。

はじめに、lstFile という ID を持つリスト ボックス コントロールと、btnDownload という ID を持つボタン コントロールがあるページを用意します(リスト1)。

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sample Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="lstFile" runat="server">
            <asp:ListItem>Sample1.csv</asp:ListItem>
            <asp:ListItem>Sample2.csv</asp:ListItem>
        </asp:ListBox><br />
        <asp:Button ID="btnDownload" runat="server" Text="ダウンロード" OnClick="btnDownload_Click" /> </div>
    </form>
</body>
</html>

リスト1.Sample.csv をダウンロードする Default.aspx

ダウンロードしたいファイルを、リスト ボックスから選択し、[ダウンロード] ボタンを押すと、HTTP ヘッダと HTTP MIME タイプを指定して、ダウンロードさせるファイルを出力します。HTTP ヘッダには、AddHeader メソッドを使い、Content-Disposition と、ダウンロードさせたいファイル名を指定します。HTTP MIME タイプの指定は、ContentType プロパティに application/octet-stream を指定します。最後に、WriteFile メソッドを使ってサーバー上にあるファイルを出力しています。(リスト2)。

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDownload.Click
        Dim strFile As String
        strFile = lstFile.SelectedValue
        If strFile <> "" Then
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile)
            Response.Flush()
            Response.WriteFile(strFile)
            Response.End()
        End If
    End Sub
End Class

リスト2.Sample.csv をダウンロードする Default.aspx.vb

Download_fig01.gif

図1 サンプル Default.aspx の表示画面

[ダウンロード] ボタンを押すと、ファイルのダウンロード ダイアログ ボックスが表示され、ファイルをダウンロードします(図2)。

Download_fig02.gif

図2 [ダウンロード] ボタンを押したとき