using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace FileToDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
byte[] data = null;
private void button1_Click(object sender, EventArgs e)
{
//读取照片
string path = txtPhoto.Text;
FileStream fs = new FileStream(path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
data = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
InsertData();
}
private void InsertData()
{
//添加到数据表中
SqlConnection conn = new SqlConnection("server=.;database=testdb;uid=sa;pwd=svse");
try
{
conn.Open();
string sql = "insert into PhotoTable(title,photo) values(@t,@p)";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter sp1 = new SqlParameter("@t", txtTitle.Text);
SqlParameter sp2 = new SqlParameter("@p", SqlDbType.Image);
sp2.Value = data;
cmd.Parameters.Add(sp1);
cmd.Parameters.Add(sp2);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
//根据标题。查找对应的图片
private void button2_Click(object sender, EventArgs e)
{
//先访问数据表,查到数据
SqlConnection conn = new SqlConnection("server=.;database=testdb;uid=sa;pwd=1234");
string sql = "select photo from PhotoTable where title='"+textBox1.Text+"'";
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count <= 0)
{
MessageBox.Show("标题不存在或没有数据");
return;
}
byte[] d = (byte[])(dt.Rows[0]["photo"]);
MemoryStream ms = new MemoryStream(d);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
页面拖个控件:
添加事件代码:
HttpPostedFile file = f1.PostedFile;
string fileName = string.Empty;
string fileExtension = string.Empty;
fileName = System.IO.Path.GetFileName(file.FileName);
if (fileName != string.Empty)
{
fileExtension = System.IO.Path.GetExtension(fileName);
Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/ImgInfo/"));
file.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/ImgInfo/") + fileName);
// 把 " ImgInfo/" + fileName 就为图片路径
}