使用ASP.Net中存储在数据库中的文件路径下载文件

时间:2014-02-27 22:20:25

标签: asp.net

我正在使用VS2012 ASP.NET网站,我有一个asp.net页面,我将文件上传到文件夹。

当我上传文件时,它将路径存储在SQL数据库tabel字段中,如~/Client_Info/text.docx,文件本身保存在文件夹中。

现在我想通过下载链接在gridview中显示我已经存储的文件。但经过一整天的搜索,我无法得到答案。有人可以帮助我吗?

protected void lnkDownload_Click(object sender, EventArgs e)
{

    LinkButton lnkbtn = sender asLinkButton;
    GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;

    int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString()); 
    string name, type; 

    using (SqlConnection con=new SqlConnection(strCon))     
    {

        using (SqlCommand cmd=new SqlCommand())
        {

            cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=@Id";
            cmd.Parameters.AddWithValue("@id", fileid);
            cmd.Connection = con;

            con.Open();     
            SqlDataReader dr = cmd.ExecuteReader();

            if(dr.Read()) 
            {
                Response.ContentType = dr["FileType"].ToString();
                Response.AddHeader("Content-Disposition", 
                                   "attachment;filename=\""
                                    + dr["FileName"] + "\"");

                Response.BinaryWrite((byte[])dr["FileData"]);
                Response.End();     
            } 
        }
    }  
}

1 个答案:

答案 0 :(得分:0)

为了将文件写入Response,您可以使用Response.WriteFile功能。它将文件的物理路径作为参数。

您可以尝试以下代码,假设文件路径正确且文件存在。

Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition", 
    "attachment;filename=\""
    + dr["FileName"].ToString() + "\"");

Response.WriteFile(Server.MapPath(dr["FileName"].ToString()));
Response.End();  
相关问题