【发布时间】:2011-02-13 22:16:59
【问题描述】:
我正在开发一个 Web 应用程序,它调用第三方开发的 Web 服务来发送/接收来自客户端数据库的数据。我正在使用 ASP.NET 3.5 C# 构建应用程序。
他们向我提供图像的方式是 BLOB 格式。我调用他们的方法,我得到的是一个带有 2 个字段“logo_name”和“logo”的数据集,这是 BLOB 字段。 我想做的是:将图像本地保存在磁盘上(以尽量减少将来对其数据库的调用)。
我一直在尝试几种不同的方法,但似乎无法正确保存图像。我已经能够在具有正确名称的文件夹中创建一个文件,但是如果我尝试查看该图像,它就不起作用。
我希望有人能给我一些示例代码来告诉我如何将 BLOB 字段保存到本地磁盘?
这是我目前拥有的代码
public static class ProductImages
{
public static string GetSchoolLogo(string schoolID, string printCodeID)
{
int v_length = 0;
string v_file_name = "";
byte[] v_file_data = null;
try
{
//Declare Web Service Variables
P_SERVICE.Service ldeService = new P_SERVICE.Service();
//Authentication Header
ldeService.AuthHeaderValue = CGlobal.GetAuthHeader(System.Web.HttpContext.Current.Session);
P_SERVICE.CDataResultOfDataSet ldeResult = null;
DataSet ds = new DataSet();
ldeResult = ldeService.GetItemLogo(schoolID, printCodeID);
ds = ldeResult.Value;
if (ds.Tables[0].Rows.Count > 0)
{
v_file_data = StrToByteArray(ds.Tables[0].Rows[0]["logo"].ToString().TrimEnd());
v_file_name = ds.Tables[0].Rows[0]["logo_name"].ToString().TrimEnd();
v_length = Convert.ToInt32(v_file_data.Length);
// Load the file in the Memory Stream
MemoryStream ms = new MemoryStream(v_file_data, 0, v_file_data.Length);
ms.Write(v_file_data, 0, v_file_data.Length);
// Open the file stream in ordre to save on the local disk
string path = HttpContext.Current.Server.MapPath("~/_imagecache/schoolLogos/").ToString();
FileStream fs = File.OpenWrite(path + schoolID + "/" + v_file_name);
fs.Write(v_file_data, 0, v_file_data.Length);
fs.Close();
// Return True if no errors occured
return "~/_imagecache/schoolLogos/" + schoolID + "/" + v_file_name;
}
else
return "~/images/noPhoto.gif";
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
//return "~/images/noPhoto.gif";
}
}
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
}
}
当我得到返回的数据类型时,它返回 System.String
Type t = ds.Tables[0].Rows[0]["logo"].GetType();
HttpContext.Current.Trace.Warn(t.FullName);
谢谢
【问题讨论】:
-
您能否发布您当前的代码,指出问题所在可能比期望有人为您发布代码更容易。
-
同意 Pharabus,发布您的代码,我确定您至少从字节数组和文件流开始 - 向我们展示您的代码。
-
谢谢大家,我的代码在上面。
-
v_file_data的一部分是什么样的?也许是base64?你确定它是以字符串的形式出现的吗?也告诉我们ds.Tables[0].Columns["logo"].DataType返回什么,我们可以澄清一些歧义。 -
返回数据集中“logo”列的一部分如下所示:@'Ïû3ìÒÇ
标签: c# asp.net image webforms blob