2014-02-27 76 views
2

我使用VS2012 ASP.NET網站,我有一個asp.net頁面,我上傳文件到一個文件夾。下載文件使用存儲在數據庫中的文件路徑在ASP.Net

當我上傳文件時,它將路徑存儲在SQL數據庫表格字段中,如~/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 [email protected]"; 
      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

您的代碼只是寫出來......無論存儲在[FileData]列中。但是,您聲明文件本身存儲在文件系統中,數據庫表只保存文件信息?您需要先從磁盤讀取文件,然後將其寫入響應。 –

回答

0

爲了向響應寫入文件,您可以使用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(); 
+0

Thansk的迴應,我有一個問題,對象「博士」被decalred作爲int。它給了我一個錯誤「不能從'對象'轉換爲'字符串'」我解決這個問題嗎? – user3362569

+0

'dr'對象是'SqlDataReader'。也許這是一個不能轉換的dr [「...」]'。我編輯了一下我的代碼,可能這是正確的。 –

相關問題