使用asp.net显示文件

问题描述:

我从sql server数据库中检索一个microsoft word文件,并在网格视图中显示该文件的id和名称。在该gridview中,我使用了两个名为Download and View的链接按钮。当我单击下载链接按钮时文件是download.Now我想要当我点击查看按钮然后文件打开并在浏览器上显示,意味着我只想查看文件内容不下载...下载我有以下代码...对于查看链接按钮以下代码中包含或排除的内容



I retrive a microsoft word file from sql server datase and display the id and name of the file in the grid view .In that gridview i have used two linked button with name Download and View.When i click the download link button the file is download.Now i want the when i click on view button then the file is open and diplay on the browser ,mean i want only to view the file content not download...for download i have the following code ... For view link button which thing is include or exclude in the following code

protected void DownloadFile(object sender, EventArgs e)
{
    int id = int.Parse((sender as LinkButton).CommandArgument);
    byte[] bytes;
    string fileName, contentType;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                sdr.Read();
                bytes = (byte[])sdr["Data"];
                contentType = sdr["ContentType"].ToString();
                fileName = sdr["Name"].ToString();
            }
            con.Close();
        }
    }
    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = contentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}





编辑(MTH):固定标记标签...



Edit (MTH): fixed markup tags...

除非客户端安装了某种可以处理解释和呈现文件的浏览器扩展,否则无法显示Word文件。在任何情况下,这都涉及客户端以这种或那种方式下载文件。



Word不是任何浏览器的本机格式,因此没有浏览器知道如何显示它没有安装扩展程序。
There is no way to display the Word file unless the client has some kind of browser extension installed that can handle interpreting and rendering the file. In any case, this involves the client downloading the file one way or another.

Word is not a native format for any browser so no browser will know how to display it without an extension installed.