日期:2013-09-24  浏览次数:21253 次

首先要创建一个表包含自段image 和 type 类型各自为image 和 vnanchar

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="ReadAndWritePicFromDB.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <FONT face="宋体"><INPUT id="File1" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 88px" type="file" name="File1" runat="server"></FONT> <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 400px; POSITION: absolute; TOP: 88px" runat="server" Text="Write" Width="104px"></asp:Button> <asp:Button id="Button2" style="Z-INDEX: 103; LEFT: 552px; POSITION: absolute; TOP: 88px" runat="server" Text="Read" Width="105px"></asp:Button> </form> </body> </HTML>



WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;

namespace ReadAndWritePicFromDB
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.WebControls.Button Button1;
private string fileName = "" ;
protected System.Web.UI.WebControls.Button Button2;
private static SqlConnection conn = null;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
ConnectDB();
}

//得到文件名
private string GetFile()
{
HttpPostedFile file = File1.PostedFile;
fileName = file.FileName;

return fileName;
}

//读取文件内容
private byte[] ReadFile()
{
FileStream file = File.OpenRead(GetFile());
byte[] content = new byte[file.Length];
file.Read(content,0,content.Length);
file.Close();

return content;
}

//连接数据库
private void ConnectDB()
{
string connStr = "Initial Catalog=;Data Source=;User ID=;Password=;";
conn = new SqlConnection(connStr);
conn.Open();
}

//写入图片到数据库中
private void WriteImage()
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "insert into images(image,type) values(@image,@type)";
comm.CommandType = CommandType.Text;
SqlParameter param = comm.Parameters.Add("@image",SqlDbType.Image);
param.Value = ReadFile();
param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
param.Value = GetContentType(new FileInfo(fileName).Extension.Remove(0,1));

if(comm.ExecuteNonQuery() == 1)
Response.Write("Successful");
else
Response.Write("Fail");

conn.Close();
}

//获取图片的后缀名
private string GetContentType(string extension)
{