4.1.2、ファイルをデータベースに保存する


2、ファイルをデータベースに保存する
アップロード

<%@ Page Language="C#" %>

<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (upFile.HasFile)
        {
            if (CheckFileType(upFile.FileName))
                srcFiles.Insert();
        }
    }
    bool CheckFileType(string fileName)
    {
        return Path.GetExtension(fileName).ToLower() == ".doc";
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        .fileList li
        {
            margin-bottom: 5px;
        }
    </style>
    <title>FileUpload Database</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblFile" Text="Word Document:" AssociatedControlID="upFile" runat="server" />
        <asp:FileUpload ID="upFile" runat="server" />
        <asp:Button ID="btnAdd" Text="Add Document" runat="server" OnClick="btnAdd_Click" />
        <hr />
        <asp:Repeater ID="rptFiles" DataSourceID="srcFiles" runat="server">
            <HeaderTemplate>
                <ul class="fileList">
            </HeaderTemplate>
            <ItemTemplate>
                <li>
                    <asp:HyperLink ID="lnkFile" Text='<%# Eval("FileName") %>' NavigateUrl='<%#Eval("Id","~/FileHandler.ashx?id={0}") %>'
                        runat="server" />
                </li>
            </ItemTemplate>
            <FooterTemplate>
                </ul>
            </FooterTemplate>
        </asp:Repeater>
    </div>
    <asp:SqlDataSource ID="srcFiles" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT Id,FileName FROM [Files]" InsertCommand="INSERT Files(FileName,FileBytes) VALUES(@FileName,@FileBytes)">
        <InsertParameters>
            <asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
            <asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
        </InsertParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

----------------------------------------
Web構成

<?xml version="1.0"?>
<!--
   ®D ? ¨? ? ? ? ASP.NET  ®| ®? ¨¬ ¨° Ì? ¨º ? ? ¡é,ê? ? ¤? ¨º
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\first.mdf;Integrated Security=True;User Instance=True"
     providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

----------------------------------------
Action

<%@ WebHandler Language="C#" Class="FileHandler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class FileHandler : IHttpHandler
{
    const string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\first.mdf;Integrated Security=True;User Instance=True";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/msword";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("Select FileBytes From Files where id=@id", con);
        cmd.Parameters.AddWithValue("@Id", context.Request["id"]);
        using (con)
        {
            con.Open();
            byte[] file = (byte[])cmd.ExecuteScalar();
            context.Response.BinaryWrite(file);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

2011-4-27 11:44 danny