2015-11-02 56 views
0

我想設置FileStream在我的應用程序工作。我很確定我遇到的問題不在我的上傳代碼中。如果我查看我的測試文件的屬性,它顯示爲46個字節。當我通過我的下載命令觀察調試步驟時,它抓取的是46字節的文件長度。FileStream下載拉頁HTML

在瀏覽器中實際下載文件時,最後一步是將一堆數據添加到文件中,特別是頁面本身的整個HTML中。我不知道爲什麼會發生這種情況。

protected void gvFilestream_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "GetFile") 
     { 

      SqlConnection objSqlCon = new SqlConnection(CS); 
      objSqlCon.Open(); 
      SqlTransaction objSqlTran = objSqlCon.BeginTransaction(); 

      SqlCommand objSqlCmd = new SqlCommand("FileGet", objSqlCon, objSqlTran); 
      objSqlCmd.CommandType = CommandType.StoredProcedure; 

      SqlParameter objSqlParam1 = new SqlParameter("@ID", SqlDbType.VarChar); 
      objSqlParam1.Value = e.CommandArgument; 

      objSqlCmd.Parameters.Add(objSqlParam1); 
      string path = string.Empty; 
      string fileType = string.Empty; 

      using (SqlDataReader sdr = objSqlCmd.ExecuteReader()) 
      { 
       while (sdr.Read()) 
       { 
        path = sdr[0].ToString(); 
        fileType = sdr[1].ToString(); 
       } 

      } 

      objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran); 

      byte[] objContext = (byte[])objSqlCmd.ExecuteScalar(); 


      SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read); 

      byte[] buffer = new byte[(int)objSqlFileStream.Length]; 
      objSqlFileStream.Read(buffer, 0, buffer.Length); 
      objSqlFileStream.Close(); 

      objSqlTran.Commit(); 
      Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(path) + fileType); 
      // Here you need to manage the download file stuff according to your need 
      Response.ContentType = "application/octet-stream"; 

      Response.BinaryWrite(buffer); 
     } 
    } 

這是我的代碼,用於下載文件的方法。下面是下載的文本文件頂部的代碼片段。我沒有把整件事放在裏面,因爲這似乎毫無意義。原始文件只包含「此文件是測試文件,用於測試」。

This document is a test document, for testing. 
<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head><title> 
    View 
</title> 

我使用的是導遊,我在網上設置此的FileStream東西了上找到,但它並沒有真正解釋每一部分都這樣做,我不知道我的方法是怎麼了。看起來好像它將在評論區域,我需要根據我的需要進行調整。

有什麼建議嗎?

回答

1

在將二進制內容寫入輸出之前,通過調用Response.Clear()來清除響應。

,以防止進一步寫入到輸出,你應該經過正確的停止請求執行:

Response.Clear(); 
Response.BinaryWrite(buffer); 
Response.End(); 
+0

我更新了我的代碼添加Response.Clear();併產生了相同的結果。 –

+0

對不起。更新我的答案(忘記完成請求..) –

+0

我不得不使用Context.ApplicationInstance.CompleteRequest();得到沒有錯誤,但這仍然產生了相同的結果。填充頁面HTML的文本文件。 –