300百分求向数据库插入图片和显示的问题
数据库为sql server,
表:student(code char(4),photo image)两个字段
求源代码
解决立刻给分
数据库为sql server,
表:student(code char(4),photo image)两个字段
求源代码
解决立刻给分
解决方案 »
- 请教一个插入语句的问题,请各位高手指点
- MySQL ODBC存储BLOB数据出错了,详情如下!
- ▲▲▲▲短信猫 群发短信问题
- 一个初级的XML问题
- 关于DataTable类中的BinginInit()、EndInit()、BingLoadData()、EndLoadData()的用法?
- 如何实现软件自动更新新版本?类似于windows的Update
- 关于编写代理服务器的问题
- 视频文件怎么边播放边下载呢,大家给点提示
- C# GDI绘图的问题
- c#中如何实现验证字符串知否为数字?不用.net提供的验证控件
- 高手请进,教我Split怎么用,谢谢!~~~
- 如何将两个DateSet填充到一个DateSet中去
//save picture
OleDbConnection mycnn=new OleDbConnection("provider=Microsoft.jet.oledb.4.0;data source=f:\\dazhu.mdb");
mycnn.Open();
OleDbCommand mycmd=new OleDbCommand("update info set picture=@a",mycnn );
FileStream mystream=new FileStream("f:\\1.jpg",FileMode.Open,FileAccess.Read);
long len=mystream.Length;
mycmd.Parameters.Add("@a",OleDbType.Binary,(int)len,"picture");
mycmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;
byte []box=new byte[len];
mystream.Read(box,0,(int)len);
mycmd.Parameters["@a"].Value=box;
//更新
mycmd.ExecuteNonQuery();
MessageBox.Show("ok");
mystream.Close();
mycnn.Close();
mycnn.Open();
MessageBox.Show("ok.mycnn.open");
OleDbCommand mycmd=new OleDbCommand("select * from info",mycnn );
OleDbDataReader myrd=mycmd.ExecuteReader();
if(myrd.Read())
{
//读取图片
byte []box=(byte [])myrd["picture"]; //构造流
Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);
stream1.Close();
}
mycnn.Close();
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=6404
namespace Drugger.WebUI.Modules
{
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Drugger.BusinessFacade;
using Drugger.Model;
using Drugger.SystemFramework;
using Drugger.WebUI.Modules;
using Drugger.WebCtrlLib; /// <summary>
/// 图片编辑控件
/// </summary>
public class PhotoEditModule: UserControl
{
protected RequiredFieldValidator valFilePhoto;
protected RegularExpressionValidator valExpFilePhoto;
protected HtmlInputFile filePhoto; private void Page_Load(object sender, System.EventArgs e){} #region 事件 // 保存相片数据
protected void btnSave_Click(object sender, EventArgs e)
{
#region 获取数据 Stream imgStream = filePhoto.PostedFile.InputStream;
int imgLength = filePhoto.PostedFile.ContentLength;
byte[]imgData = new byte[imgLength];
int n = imgStream.Read(imgData, 0, imgLength); #endregion if (Page.IsValid)
{
#region 保存数据到数据库 int retVal = - 1;
PhotoModel photoModel = new PhotoModel();
PhotoSystem photoSystem = new PhotoSystem();
PhotoModel.PhotoRow row = photoModel.Photo.NewPhotoRow(); row.Photo = imgData; photoModel.Photo.Rows.Add(row);
retVal = photoSystem.Insert(photoModel); #endregion
}
} #endregion #region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
} /// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load); }
#endregion
}
}前台代码
<TABLE cellSpacing="1" cellPadding="3" width="100%" border="0">
<TR>
<TD>
<INPUT id="filePhoto" type="file" name="filePhoto" runat="server">
<asp:RequiredFieldValidator id="valFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="请选择图片"
Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="valExpFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="图片格式错误"
Display="Dynamic" ValidationExpression="[a-zA-Z]:\\(.+\\)*.+(\.gif|\.jpeg|\.jpg)"></asp:RegularExpressionValidator>
<P>注:上传的图片必须为gif或jpeg格式,图片规格默认为94×114(最佳浏览效果)</P>
</TD>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="1" CELLPADDING="3">
<TR>
<TD width="40"> </TD>
<TD height="40">
<asp:Button id="btnSave" runat="server" Text="保存" Width="60" OnClick="btnSave_Click" />
<asp:HyperLink id="hlkReturn" runat="server" Text="返回" Absoluted="True" CssClass="Button" Width="60" />
</TD>
</TR>
</TABLE>显示图片前台代码
<%@ Page language="c#" Codebehind="Picture.aspx.cs" AutoEventWireup="false" Inherits="Drugger.WebUI.Modules.Picture" EnableSessionState="False" enableViewState="False" %>后台代码
namespace Drugger.WebUI.Modules
{
using System;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Drugger.BusinessFacade;
using Drugger.SystemFramework; /// <summary>
/// 图片显示Web页
/// </summary>
public class Picture: Page
{
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
int photoId = 0;
string photoIdText = Request.QueryString.Get("photoId");
photoId = (int)photoIdText;
byte[]photo = (new PhotoSystem()).GetPhotoByPhotoID(photoId); if (photo != null)
{
Response.ContentType = "image/*";
Response.BinaryWrite(photo);
}
}
} #region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
} /// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
}
}数据库提取代码:
/// <summary>
/// 获取图片
/// </summary>
/// <param name="photoId">图片ID</param>
/// <returns>图片</returns>
public byte[]GetPhotoByPhotoID(int photoId)
{
byte[]photo = null;
string spString = "GetPhotoByPhotoID"; SqlParameter[]parms = SqlHelperParameterCache.GetSpParameterSet
(AccessCommon.ConnectionString, spString);
parms[0].Value = photoId; using(SqlDataReader rdr = SqlHelper.ExecuteReader
(AccessCommon.ConnectionString, CommandType.StoredProcedure, spString,
parms))
{
if (rdr.Read())
{
if (!rdr.IsDBNull(0))
photo = (byte[])rdr[0];
}
} return photo;
}
先建一个类,Copy可用..........
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary; //引入供序列化Image对象使用namespace Common
{
/// <summary>
/// 实现Image与byte[]之间的转换
/// </summary>
public class ReadWriteImage
{
private ReadWriteImage(){}
/// <summary>
/// 将byte[]转换为Image
/// </summary>
/// <param name="bytes">字节数组</param>
/// <returns>Image</returns>
public static Image ReadImage(byte[] bytes)
{
MemoryStream ms=new MemoryStream(bytes,0,bytes.Length);
BinaryFormatter bf = new BinaryFormatter();
object obj=bf.Deserialize(ms);
ms.Close();
return (Image)obj;
}
/// <summary>
/// 将Image转换为byte[]
/// </summary>
/// <param name="image">Image</param>
/// <returns>byte[]</returns>
public static byte[] ConvertImage(Image image)
{
MemoryStream ms=new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,(object)image);
ms.Close();
return ms.ToArray();
}
}
}
FileStream stream=new FileStream("c:\\w.jpg",FileMode.Open,FileAccess.Read);
byte[] blob=new byte[stream.Length];
stream.Read(blob,0,(int)stream.Length);
stream.Close();
string source="server=csl;database=StudentDB;uid=sa;pwd=''";
sqlcon=new SqlConnection(source);
try
{
sqlcon.Open();
string sql="insert into photo(code,photo) values('0001',@photo)";
SqlCommand command=new SqlCommand(sql,sqlcon);
cmd.Parameters.Add("@photo",blob);
//cmd.Parameters.Add("@photo", SqlDbType.Image, blob.Length).Value = blob;
cmd.ExecuteNonQuery();
}
catch(Exception e1)
{
Console.WriteLine("shiba");
}
finally
{
sqlcon.Close();
}
}在插入数据库时,不包任何错误,但数据库中没有数据我的数据库是sqlserver 表结构为photo(code char(4),photo image)
mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
mycnn.Open();
SqlCommand mycmd=new SqlCommand("update picture set picture=@a where ID=1",mycnn);
FileStream mystream=new FileStream("f:\\1.jpg",FileMode.Open,FileAccess.Read);
long len=mystream.Length;
mycmd.Parameters.Add("@a",SqlDbType.Image,(int)len,"picture");
mycmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;
byte []box=new byte[len];
mystream.Read(box,0,(int)len); mycmd.Parameters["@a"].Value=box;
//更新
mycmd.ExecuteNonQuery();
MessageBox.Show("ok");
mystream.Close();
mycnn.Close();
mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
mycnn.Open();
MessageBox.Show("ok.mycnn.open");
SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
SqlDataReader myrd=mycmd.ExecuteReader();
if(myrd.Read())
{
//读取图片
if(!myrd.IsDBNull(1))
{
byte []box=(byte [])myrd[1];
//构造流
Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);
stream1.Close();
}
else
{ MessageBox.Show("该字段是NULL");
}
}
mycnn.Close();
}
catch(Exception my)
{
MessageBox.Show(my.Message.ToString()); }
cmd.Parameters["@photo"].Value = ConvertImage(System.Drawing.Image.FromFile("c:\\w.jpg"));
mycnn.Open();
MessageBox.Show("ok.mycnn.open");
SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
SqlDataReader myrd=mycmd.ExecuteReader();
if(myrd.Read())
{
//读取图片
if(!myrd.IsDBNull(1))
{
byte []box=(byte [])myrd[1];
//构造流
Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);
stream1.Close();
}
else
{ MessageBox.Show("该字段是NULL");
}
}
mycnn.Close();
}
catch(Exception my)
{
MessageBox.Show(my.Message.ToString()); }
http://www.pcsky.cn/article/list.asp?id=774看不懂再问
http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506
显示:
http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1
http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1