ASP.NET2.0中將資料庫欄位中儲存的檔案顯示出來

來源:互聯網
上載者:User
 在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();
%>
更多的內容:奧凱瑞爾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.