【问题标题】:How to upload images to mysql database using C#?如何使用 C# 将图像上传到 mysql 数据库?
【发布时间】:2014-04-25 05:57:34
【问题描述】:

我正在尝试将图像从 Windows 应用程序插入到 mysql 数据库。在尝试这样做时,我遇到了以下错误

“无法将 'System.Byte[]' 类型的对象转换为 'System.IConvertible' 类型。”

public void LoadImages()          
{        
    MySqlConnection cn = new MySqlConnection(connstring);        
    cn.Open();    
    string image = txtLogo.Text;    
    byte[] ImageData;    
    FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);    
    BinaryReader br = new BinaryReader(fs);    
    ImageData = br.ReadBytes((int)fs.Length);    
    br.Close();    
    fs.Close();    
    MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(@Images,'"+txtEmailId.Text+"')", cn);    
    cmd.Parameters.AddWithValue("@Images", MySqlDbType.LongBlob).Value = ImageData;    
    cmd.ExecuteNonQuery();    
    cn.Close();    
}

请帮助清除此错误。

【问题讨论】:

  • 在女巫线发生错误?
  • 当我调试代码错误显示在 executenonquery(;

标签: c# mysql


【解决方案1】:

应该这样做:

MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(?Images,'" + txtEmailIdText + "')", cn);

MySqlParameter parImage = new MySqlParameter();
parImage.ParameterName = "?Images";
parImage.MySqlDbType = MySqlDbType.MediumBlob;
parImage.Size = 3000000;
parImage.Value = ImageData;//here you should put your byte []

cmd.Parameters.Add(parImage);
cmd.ExecuteNonQuery();

这可能是检查图像是否已存储到数据库的一种方法

//write your code to get the record from db to byte[] ImageData;
public Image byteArrayToImage(byte[] byteBLOBData )
{
    MemoryStream ms = new MemoryStream(byteBLOBData );
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

这样打电话

PictureBox picture = new PictureBox();
picture.Image = byteArrayToImage(ImageData);
Controls.Add(picture);

【讨论】:

  • 当你得到它时,你必须处理字节并将它们显示为图像
  • 取决于你在做什么样的应用程序 WPF WinForm ASP.NET?
  • ASP.NET (C#) 其 windows 应用程序
  • 这应该可以帮助您决定如何继续显示图像stackoverflow.com/questions/18177351/…。至于将图像写入数据库,我认为您有答案
  • @user3531533 你怎么知道不是?
猜你喜欢
  • 1970-01-01
  • 2016-05-26
  • 2017-12-07
  • 2013-07-17
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2018-08-10
  • 2015-01-01
相关资源
最近更新 更多