asp教程.net 上传文件保存到数据库教程的方法( C#)
C#做一个小的程序,其中用涉及到了照片的存取与显示,在网上搜索了很多有关的代码,但是几乎没有完整,大部分只是其中的存取或者显示代码,笔者将其整理了一下,形成了一个集照片上传到数据库、照片显示于一体的小模块。 using
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//选择按钮事件处理
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = "C:";
openFileDialog1.Filter = "图片文件 (*.jpg)|*.jpg";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
//上传按钮事件处理
private void button2_Click(object sender, EventArgs e)
{
Save(PhotoToArray(textBox1.Text.ToString()));
}
//将图片信息转换成二进制信息
private byte[] PhotoToArray(string path)
{
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bufferPhoto = new byte[stream.Length];
stream.Read(bufferPhoto, 0, Convert.ToInt32(stream.Length));
stream.Flush();
stream.Close();
return bufferPhoto;
}
//把二进制的图片插到数据库
private void Save(byte[] image)
{
string sql = "insert into Photo(photo_Info) values(@photo)";
SqlParameter param = new SqlParameter();
param = new SqlParameter("@photo", SqlDbType.Image);
param.Value = image;
SqlCommand commd = new SqlCommand(sql, DBhelper.con);
commd.Parameters.Add(param);
try
{
DBhelper.con.Open();
commd.ExecuteNonQuery();
MessageBox.Show("您已经把图片成功的插入数据库!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DBhelper.con.Close();
}
}
//显示图片按钮事件处理
private void button3_Click(object sender, EventArgs e)
{
string strSQL = "Select [photo_Info] From [Photo] Where [photo_Id]=(@photo)";
SqlParameter param = new SqlParameter();
param = new SqlParameter("@photo", SqlDbType.Int);
param.Value = comboBox1.Text.ToString();
SqlCommand cmd = new SqlCommand(strSQL, DBhelper.con);
cmd.Parameters.Add(param);
DBhelper.con.Open();
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
try
{
reader.Read();
MemoryStream ms = new MemoryStream((byte[])reader["photo_Info"]);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
this.pictureBox1.Image = image;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DBhelper.con.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“myPhotoDataSet.Photo”中。您可以根据需要移动或移除它。
this.photoTableAdapter.Fill(this.myPhotoDataSet.Photo);
}
}
}
摩尔庄园 安卓官方版v2.9.24091002S
摩尔庄园很多小伙伴一定都在小时候玩过,但随着我们年龄的增长淡
梦幻庄园最新版 官方正版v1.0.0
梦幻庄园是一款非常好玩的模拟经营类游戏,玩家在游戏中有一个属
合并梦幻岛免内购版 v2.1.0
合并梦幻岛无限内购版是游戏的破解版本,在该版本中为玩家解锁了
无悔华夏魅族版 2025最新版v3.5.194
无悔华夏魅族版是一款超级好用的模拟经营游戏。在这里玩家们需要
月影别墅官方安装包2025版 安卓版v2.3.24
月影别墅官方安装包2025版是一款匠心独具的乙女向剧情游戏,