使用文件上传控件将图像插入MySQL数据库 [英] Inserting an image into MySQL database using file upload control
本文介绍了使用文件上传控件将图像插入MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Visual Studio中的文件上传控件将图像插入MySQL数据库.我正在使用带有ODBCc和.NET连接器的ASP.NET 3.5和MySQL Community Server.
I would like to insert the image into a MySQL database using the file upload control in Visual Studio. I am using ASP.NET 3.5 and MySQL Community Server with ODBCc and .NET Connectors.
推荐答案
此处有一些代码会将发布的文件拉入字节数组.然后将其传递给MySQL.假定 varbinary
列数据类型.根据需要进行修改.
Here some code that will pull the posted file into a byte array. It'll then pass it down to MySQL. Assumes a varbinary
column data type. Modify as you need.
if(FileUploadControl.HasFile)
{
try
{
byte[] img = new byte[FileUploadControl.PostedFile.ContentLength- 1];
img = FileUploadControl.FileBytes;
InsertImg(img);
}
catch(Exception ex)
{
}
}
....
public void InsertImg(byte[] img) //untested code
{
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"INSERT INTO MyTable(MyImage) VALUES (@Img)";
cmd.Parameters.Add("@Img", System.Data.SqlDbType.VarBinary); //or SqlDbType.Image
cmd.Parameters["@Img"].Value = img;
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
这篇关于使用文件上传控件将图像插入MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文