在C#中上传图片 [英] upload picture in c#
本文介绍了在C#中上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请提供代码以通过c#中的图片框上传和保存图片..
这是我上传的代码,但是出现异常处理错误,请帮帮我..
please give the code for upload and save picture through picturebox in c#..
this is the code for upload which i made but exception handling error comes please help me out..
private void btnupload_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog(this);
openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
byte[] image;
string fileName =openFileDialog1.FileName;
FileStream fs = new FileStream(fileName, FileMode.Open);
BinaryReader reader = new BinaryReader(fs);
image = reader.ReadBytes((int)fs.Length);
fs.Close();
SqlConnection conn = new SqlConnection("connectionString");
conn.Open();
string query = "Insert into pictures (name,images) values(@name,@images)";
SqlCommand comm = new SqlCommand(query, conn);
comm.Parameters.AddWithValue("name", Path.GetFileName(strFn).ToString());
comm.Parameters.AddWithValue("images", image);
comm.ExecuteNonQuery();
MessageBox.Show("Record Added");
conn.Close();
bind();
pictureBox1.Image = new Bitmap(strFn);
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
感谢
thanks
推荐答案
您发送的邮件
Your sending
comm.Parameters.AddWithValue("name", Path.GetFileName(strFn).ToString());
You should send string fileName;
尝试
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
在buttonupload的点击事件中尝试
at click event of buttonupload try
byte[] imageData = ReadFile(openFileDialog1.FileName);
并将这些imagedata值作为
传递给sqlcommand参数
and pass these imagedata value to sqlcommand parameter as
comm.Parameters.AddWithValue("images",(object)imageData);
这篇关于在C#中上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文