当我使用SQL语句时
SELECT File_Data
FROM Attachments
WHERE UserID = '12345' AND FileNames = 'testing1.jpg'
图片下载后看起来很棒。但是,如果我放入一个存储过程,它会在我名为 C:\Testing\
的文件夹中创建 testing1.jpg
文件,但它不会在图像中写入数据,并且它不会正确显示。下面是我必须调用存储过程并将其编写出来的内容。关于我在这里做错了什么有什么想法吗?
用于测试目的:
- strfilename =
testing1.jpg
- 用户 ID =
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
最佳答案
一些建议:
在 byte[] fileData = (byte[])dr.GetValue(0);
处设置一个断点,以查看在将数据写入文件之前是否返回任何数据。
使用CommandBehavior.Default
当使用 CommandBehavior.SequentialAccess
时尝试使用 GetBytes SqlDataReader 的方法。
作为最后的手段,将您的 SP 更改为返回 User_ID,以检查是否返回任何内容。
关于c# - 从 SQL 中检索 VarBinary 数据并保存图像/文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21705849/