数据库结构:
id int
img image
type varchar50
leng varchar50
录入和管理:
aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form ></asp:SqlDataSource>
</table>
</div>
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (UpFile.HasFile)
{
int FileLength = UpFile.PostedFile.ContentLength;
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = UpFile.PostedFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray, 0, FileLength);
//建立SQL Server链接
using (SqlConnection Con = new SqlConnection("server=.;database=imgTest;uid=sa;pwd=sa"))
{
String SqlCmd = "INSERT INTO imgTable (img,type,leng) values (@img,@type,@leng)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@img", SqlDbType.Image, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@type", SqlDbType.VarChar, 50).Value = UpFile.PostedFile.ContentType;
CmdObj.Parameters.Add("@leng", SqlDbType.Int).Value = FileLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
}
Response.Write("<script>alert('ok!');</script>");
}
}
}
读取:
aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Show.aspx.cs" Inherits="Show" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form >
<div>
</div>
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Show : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["imgId"]))
{
string imgId = Request.QueryString["imgId"];
using (SqlConnection Con = new SqlConnection("server=.;database=imgTest;uid=sa;pwd=sa"))
{
Con.Open();
SqlCommand CmdObj = new SqlCommand("select * from imgTable where ]);
Response.End();
}
}
}
}