2014-02-11 60 views
1

當我使用SQL語句從SQL檢索varbinary數據並保存圖像/文件

SELECT File_Data 
FROM Attachments 
WHERE UserID = '12345' AND FileNames = 'testing1.jpg' 

圖像下載和看上去很不錯。但是如果我放入存儲過程,它將在我的文件夾0123.中創建文件testing1.jpg,但它不會在圖像中寫入數據,並且不會正確顯示。下面是我必須調用存儲過程並寫出來的內容。關於我在這裏做錯的任何想法?

出於測試目的:

  • strfilename = testing1.jpg
  • 的userid = 12345

代碼:

protected void LoadFiles(string strfilename, int userid) 
{ 
    string fullname = strfilename; 

    using (SqlConnection cn = new SqlConnection(conn_string)) 
    { 
     cn.Open(); 

     using (SqlCommand cmd = new SqlCommand("GET_ATTACHMENT", cn)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure;     

      SqlParameter p1 = new SqlParameter("@FileName", SqlDbType.NVarChar, 255); 
      p1.Direction = ParameterDirection.Input; 
      p1.Value = strfilename; 
      cmd.Parameters.Add(p1); 

      SqlParameter p2 = new SqlParameter("@User_ID", SqlDbType.Int); 
      p2.Direction = ParameterDirection.Input; 
      p2.Value = userid; 
      cmd.Parameters.Add(p2); 

      // Tried using this statement but it did not work. // 
      SqlParameter pSub = new SqlParameter("@File_Data", SqlDbType.VarBinary); 
      pSub.Direction = ParameterDirection.ReturnValue; 
      cmd.Parameters.Add(pSub); 
      Response.Write(pSub); 

      // *** *** ///      
      using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) 
      { 
       if (dr.Read()) 
       { 

        // For some reason the data being returned is blank 
        // When I run it in SQL I get data being returned. 

        byte[] fileData = (byte[])dr.GetValue(0); 

        using (System.IO.FileStream fs = new System.IO.FileStream("C:\\Testing\\" + (fullname), System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) 
        { 
         using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) 
         { 
          bw.Write(fileData); 
          bw.Close(); 
         } 
        } 
       } 

       dr.Close(); 
      } 
     } 
    } 
} 

SQL Server存儲過程:

ALTER PROCEDURE [dbo].[GET_ATTACHMENT] 
    @User_ID int, 
    @FileName nvarchar(250) 
AS 
BEGIN 
    SET NOCOUNT ON; 

DECLARE @FileData varbinary(max) 

    Set @FileData = (SELECT File_Data FROM Attachments 
     WHERE UserID = @User_ID and 
     FileNames = @FileName); 

    SELECT @FileData 

END 

回答

0

幾點建議:

byte[] fileData = (byte[])dr.GetValue(0);設置一個破發點,以查看是否有任何數據,將其寫入文件之前返回。

使用CommandBehavior.Default

當使用CommandBehavior.SequentialAccess嘗試使用SqlDataReader的的GetBytes方法。

作爲最後的手段,更改您的SP返回User_ID,只是爲了檢查是否返回任何內容。

+0

返回的數據是:System.Byte [] – mrmcg

+0

返回的值爲空白。 – mrmcg

+0

@mrmcg即使使用'CommandBehavior.Default'?你可以運行任何存儲過程嗎? –

相關問題