印刷用ページ      送信     
クリックして評価とフィードバックをお寄せください
MSDN
MSDN ライブラリ
テクニカルドキュメント
.NET 開発
プログラミング Tips
 データベースにある画像データをダウンロードする方法
データベースにある画像データをダウンロードする方法

最終更新日 2006 年 4 月 28 日

download1.gif サンプル コードのダウンロード (aspnettips_DataBaseImage3.msi, 267 KB)

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

今回は、データベースからデータを読み込む処理などが共通なので、データベースにある画像データを表示する方法で紹介したサンプルを元に、画像データをダウンロードする機能を追加します。

はじめに、OutputDBImage.aspx.vb に、リスト1 にある赤文字のコードを追加します。ダウンロード用のコードは、HTTP クエリ文字列の mode で「download」が指定されたときに処理します。
画像データをダウンロードさせるには、HttpResponse の ContentType プロパティに「application/octet-stream」を指定し、HttpResponse の AddHeader メソッドを使い、ダウンロード ダイアログに表示するファイル名を指定した Content-Disposition ヘッダを追加します。


Partial Class OutputDBImage
    Inherits System.Web.UI.Page
    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' ID 取得
        Dim intId As Integer = 0
        Integer.TryParse(Request.QueryString("id"), intId)
        ' DB を開く
        Dim oleConn As New Data.OleDb.OleDbConnection()
        oleConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
        AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "IMAGE.MDB"
        oleConn.Open()
        ' データの読込み
        Dim cmdSelect As New Data.OleDb.OleDbCommand
        cmdSelect.Connection = oleConn
        cmdSelect.CommandText = "SELECT * FROM IMGINFO WHERE ID=?"
        cmdSelect.Parameters.Add("ID", Data.OleDb.OleDbType.Integer, 4, "ID").Value = intId
        Dim rdrDB As Data.OleDb.OleDbDataReader = cmdSelect.ExecuteReader()
        If rdrDB.Read() Then
          If Request.QueryString("mode") = "download" Then
                Response.HeaderEncoding = Text.Encoding.GetEncoding("Shift-JIS")
                Response.ContentType = "application/octet-stream"
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(rdrDB("NAME") + ".gif"))
            Else
                Response.ContentType = rdrDB("IMGTYPE")
           End If
            Response.Flush()
            Response.BinaryWrite(CType(rdrDB("IMGDATA"), Byte()))
            Response.End()
        End If
        cmdSelect.Dispose()
        ' DB を閉じる
        oleConn.Close()
        oleConn.Dispose()
    End Sub
End Class

リスト1.OutputDBImage.aspx.vb に追加するコード

ダウンロードする画像を選択するページを作成する

選択された画像のデータをダウンロードするボタンを追加します (リスト2、およびリスト3) 。ボタンが押されたとき、HttpResponse の Redirect メソッドを使い、HTTP クエリ文字列として、id に画像データの ID と、mode に「download」を指定した OutputDBImage.aspx へリダイレクトします。

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head runat="server">
    <title>Sample Page</title>
</head>
<body>
    <form id="MyForm" runat="server">
    <div>
            <table border="1">
            <tr>
                <td>
                    画像番号
                </td>
                <td>
                    <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"></asp:ListBox>
                </td>
            </tr>
            <tr>
                <td>
                    イメージ
                </td>
                <td>
                    <asp:image ID="Image1" ImageUrl="~/dummy.gif" runat="server"></asp:image>
                </td>
            </tr>
           <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="ButtonDownload" Text="ダウンロード" Runat="server" UseSubmitBehavior="False"></asp:Button>
                </td>
            </tr>
            </table>
    </div>
    </form>
</body>
</html>

リスト2.Default.aspx

図

図1 Default.aspx のデザイナ画面

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If ListBox1.Items.Count < 1 Then
            ' DB を開く
            Dim oleConn As New Data.OleDb.OleDbConnection()
            oleConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
            AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "IMAGE.MDB"
            oleConn.Open()
            ' データの読込み
            Dim cmdSelect As New Data.OleDb.OleDbCommand
            cmdSelect.Connection = oleConn
            cmdSelect.CommandText = "SELECT * FROM IMGINFO"
            Dim rdrDB As Data.OleDb.OleDbDataReader = cmdSelect.ExecuteReader()
            ListBox1.DataSource = rdrDB
            ListBox1.DataTextField = "NAME"
            ListBox1.DataValueField = "ID"
            ListBox1.DataBind()
            cmdSelect.Dispose()
            ' DB を閉じる
            oleConn.Close()
            oleConn.Dispose()
        End If
    End Sub
    Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Image1.ImageUrl = "~/OutputDBImage.aspx?id=" + Request("ListBox1")
    End Sub
   Protected Sub ButtonDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonDownload.Click
        Response.Redirect("~/OutputDBImage.aspx?id=" + Request("ListBox1") + "&mode=download")
    End Sub
End Class

リスト3.Default.aspx.vb

図2. Default.aspxの実行結果

© 2008 Microsoft Corporation.All rights reserved. 使用条件  |  商標  |  プライバシー
Page view tracker