【问题标题】:Updating database Image just stores 0x更新数据库 Image 只存储 0x
【发布时间】:2015-02-28 13:58:00
【问题描述】:

我有一个存储用户信息的表,它是通过加载一个 XML 文件来填充的。 在该表中,我有一个用于在 XML 文件中设置为“null”的所有用户的图像类型列。 当我尝试更新该列并设置图像时,问题就出现了,它只存储“0x”。

这是桌子:

create table User(
ID INTEGER PRIMARY KEY,
name VARCHAR(50),
foto IMAGE,
email VARCHAR(100))

这是我的更新代码:

protected void addFoto_Click(object sender, EventArgs e)
{
    Byte[] imgByte = null;
    if (file_upload.PostedFile != null)
    {
        HttpPostedFile File = file_upload.PostedFile;
        File.InputStream.Position = 0;
        imgByte = new Byte[File.ContentLength];
        File.InputStream.Read(imgByte, 0, File.ContentLength);
    }
    string sql = "update User set foto = @foto where email= @email";
    using(SqlCommand cmd = new SqlCommand(sql, con.getConexion()))
    {
        cmd.Parameters.AddWithValue("@email", Txtemail.Text.ToString());
        cmd.Parameters.AddWithValue("@foto", imgByte);
        con.open();
        cmd.ExecuteNonQuery();
        con.close();
    }
}

我尝试添加

File.InputStream.Position = 0;

作为这篇文章中的答案,但仍然没有用。

Can't save byte[] array data to database in C#. It's saving 0x

我还尝试使用以下代码使用列类型 VARBINARY(MAX):

string sql = "update User set foto = @foto where email= @email";
using (SqlCommand cmd = new SqlCommand(sql, con.getConexion()))
{
   Stream fs = file_upload.PostedFile.InputStream;
   BinaryReader br = new BinaryReader(fs);
   Byte[] bytes = br.ReadBytes((Int32)fs.Length);
   cmd.Parameters.AddWithValue("@email", Txtemail.Text.ToString());
   cmd.Parameters.Add("@foto", SqlDbType.Binary).Value = bytes;
   con.open();
   cmd.ExecuteNonQuery();
   con.close();
}

其中刚刚存储了 0x000000... 最后,我还尝试直接添加图像:

System.Drawing.Image imag = System.Drawing.Image.FromStream(file_upload.PostedFile.InputStream);
cmd.Parameters.Add("foto", SqlDbType.Binary, 0).Value = ConvertImageToByteArray(imag, System.Drawing.Imaging.ImageFormat.Jpeg);

没有结果。

以下是调试时 file_upload 的值:

我觉得奇怪的是它有一个已发布的文件但没有字节......

如果有人能告诉我我做错了什么,我将不胜感激,如果我的英语不完美,请原谅。

【问题讨论】:

  • 使用 varbinary 字段的大小。 .Add("@binaryValue", SqlDbType.VarBinary, 8000)
  • @LuisDiego 你能检查这是否为空:file_upload.PostedFile?通过单步执行代码?
  • @zaitsman 不,它返回这个值“{System.Web.HttpPostedFile}”
  • @Luba 我在 "cmd.Parameters.Add("@foto", SqlDbType.VarBinary, 8000).Value = bytes;" 行中添加了您所说的内容但它仍然在数据库中存储 0x。
  • @zaitsman 我添加了调试控制台,如果你能告诉我那里发生了什么...

标签: c# asp.net xml image sql-update


【解决方案1】:

问题是我在 Page_Load 中执行了一个 PostBack,它刷新了页面以显示文件名,但同时它将 PostedFile 重置为空。

我的解决方案是创建一个全局 HttpPostedFile 变量,将发布的文件存储在 PostBack 中以供将来使用。

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多