将 BLOB 作为 Image C# 保存到磁盘

发布于 2024-08-31 06:31:26 字数 2934 浏览 0 评论 0原文

我正在开发一个 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);

谢谢

I am developing a web application that calls web services developed by a third party to send/receive data from a clients database. I am building the application using ASP.NET 3.5 C#.

The way that they are providing me images is in BLOB format. I call their method and what I get back is a DataSet with 2 fields "logo_name" and "logo" which is the BLOB field.
What I want to do is: Save the image locally on the disk (to minimize calls to their database in the future).

I have been playing around with a couple of different ways of doing this but cannot seem to get the image to save correctly. I have been able to create a file in a folder with the correct name but if I try to view the image it does not work.

I was hoping someone could give me some sample code to show me how to save a BLOB field to the local disk?

Here is the code I currently have

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);
        }
    }


}

When I get the Type of data being returned it returns System.String

Type t = ds.Tables[0].Rows[0]["logo"].GetType();
HttpContext.Current.Trace.Warn(t.FullName);

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少跟Wǒ拽 2024-09-07 06:31:26

您的行:

v_file_data = StrToByteArray(ds.Tables[0].Rows[0]["logo"].ToString().TrimEnd()); 

实际上应该是:

v_file_data = ds.Tables[0].Rows[0]["logo"] as Byte[];

您使用的方法不会以相同的方式对字节进行编码和解码。

Your line:

v_file_data = StrToByteArray(ds.Tables[0].Rows[0]["logo"].ToString().TrimEnd()); 

Should really be:

v_file_data = ds.Tables[0].Rows[0]["logo"] as Byte[];

The method you were using will not encode and decode the bytes in the same way.

巴黎盛开的樱花 2024-09-07 06:31:26

好吧,看起来网络服务对你没有任何帮助。他们确实应该返回一个字节数组。但无论如何,该字符串绝对不是base64,也绝对不是ascii。

让我们在黑暗中尝试一下这种疯狂的刺杀:

v_file_data = Encoding.UTF8.GetBytes(ds.Tables[0].Rows[0]["logo"]);

Ok, so it looks like the web service is doing you no favors. They really should be returning a byte array. but anyway, the string is definitely not base64 and definitely not ascii.

Lets try this wild stab in the dark:

v_file_data = Encoding.UTF8.GetBytes(ds.Tables[0].Rows[0]["logo"]);
我是男神闪亮亮 2024-09-07 06:31:26

试试这个:

// replace this line:
//v_file_data = StrToByteArray(ds.Tables[0].Rows[0]["logo"].ToString().TrimEnd());

// with this block:
string base64string = ds.Tables[0].Rows[0]["logo"] as string;

if (base64string != null)
{
    v_file_data = System.Convert.FromBase64String(v_file_data);
}

获取字节数组并使用其余代码将其加载到文件中。

哈....

Try this:

// replace this line:
//v_file_data = StrToByteArray(ds.Tables[0].Rows[0]["logo"].ToString().TrimEnd());

// with this block:
string base64string = ds.Tables[0].Rows[0]["logo"] as string;

if (base64string != null)
{
    v_file_data = System.Convert.FromBase64String(v_file_data);
}

Take the byte array and load it to file using the rest of your code.

HTH....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文