ASP.NET2.0中将数据库字段中存储的文件显示出来

 在web应用中有时要求将存储在字段中的文件显示出来,这些文件以BLOB方式存在数据库中。显示时吐出到客户端浏览器。下面是示例代码。表名是ATTACHMENTS ,BLOB字段名ATTACHMENT_CONTENT。

<%@ Page Language="C#" EnableTheming="false" ValidateRequest="false" StylesheetTheme=""%>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%
    SqlConnection conn;
    SqlCommand comm;

    string sID = Request.QueryString["sID"].ToString();
    conn = new SqlConnection();
    comm = new SqlCommand();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["HS2005ConnectionString"].ConnectionString;
    comm.Connection = conn;
    conn.Open();
    comm.CommandText = @"SELECT ATTACHMENT_CONTENT,FILE_NAME,FILE_TYPE FROM ATTACHMENTS where ATTACHMENT_ID='" + sID + "'";
    SqlDataReader sdr = comm.ExecuteReader();
    if (sdr.Read())
    {
        Response.Clear();
        Response.ClearHeaders();
        string fn = sdr["FILE_NAME"].ToString();
        Response.Expires = 0;
        Response.Buffer = true;
        Response.Charset = "utf-8";
        this.EnableViewState = false;
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = sdr["FILE_TYPE"].ToString();
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fn);  //attachment改为inline则显示在浏览器中。
        Response.ContentType = sdr["FILE_TYPE"].ToString();
        Response.BinaryWrite((byte[])sdr["ATTACHMENT_CONTENT"]);
    }
    sdr.Close();
    conn.Close();
%>
更多的内容:奥凯瑞尔

posted on 2006-03-29 14:22  林岳  阅读(878)  评论(3编辑  收藏  举报