高分请教:用C#如何将一个图片文件保存到SQL Server数据库?

conan1211 2005-12-28 03:48:25
rt.
...全文
265 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
huangyubinde 2005-12-28
  • 打赏
  • 举报
回复
用二进制数组 byte []
xiaoyezi001 2005-12-28
  • 打赏
  • 举报
回复
aa
holym 2005-12-28
  • 打赏
  • 举报
回复
看看这个吧
http://blog.csdn.net/holym/category/158048.aspx
conan1211 2005-12-28
  • 打赏
  • 举报
回复
原来如此啊,谢谢各位大侠了,那个保存文件的字段用varchar可以吗?
fromVbToCs 2005-12-28
  • 打赏
  • 举报
回复
网上很多啊,搜一下
pgy8288 2005-12-28
  • 打赏
  • 举报
回复
倒,楼上写的也太烦琐了吧
最主要是获取PostedFile.inputstream的值
后面的相信楼主肯定会的撒
jinqinghai 2005-12-28
  • 打赏
  • 举报
回复
是啊,存其他类型的文件也同样适用


conan19771130 2005-12-28
  • 打赏
  • 举报
回复
原理是村一个二进制
zwfhome1 2005-12-28
  • 打赏
  • 举报
回复
private void Readphoto(string id)
{
try
{ //读取图象
string ls_sql="select photo from p_ry_photo where id='"+id+"'";
this.picPhoto.Image=null;
this.picPhoto.Refresh();
SqlCommand cmd=new SqlCommand(ls_sql,CommonVar.SqlConDataBase);
SqlDataReader reader=cmd.ExecuteReader();
while(reader.Read())
{
byte[] b = (byte[])reader[0];
MemoryStream s = new MemoryStream(b);
Bitmap bmp = new Bitmap(s);
System.Drawing.Image image = bmp;
picPhoto.Image = image;
s.Close();
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
zwfhome1 2005-12-28
  • 打赏
  • 举报
回复
保存
sql="insert into p_ry_photo(id,photo) values ('"+id+"',@i)";
SqlCommand cmd=new SqlCommand(sql,CommonVar.SqlConDataBase);
MemoryStream s = new MemoryStream();
picPhoto.Image.Save(s,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] b = s.ToArray();
s.Close();
cmd.Parameters.Add("@i",SqlDbType.Image,(int)b.Length);
cmd.Parameters["@i"].Value=b;
cmd.ExecuteNonQuery();
孟子E章 2005-12-28
  • 打赏
  • 举报
回复
我们可以把任意类型的文件保存到SQL Server中,在进行例子之前,先建立测试用表格,TestFile.sql:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TestFiles]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TestFiles]
GO

CREATE TABLE [dbo].[TestFiles] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[MyFileName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[FileType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[MyFile] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

下面创建上传表单:

一旦提交了表单,我们使用HtmlInputFile类的PostedFile属性来访问我们上载的文件,用HttpPostedFile类的属性和方法来进行读取、保存上载文件和得到上载文件的其它信息。这里我们不使用SaveAs方法,因为它是用来保存文件的。我们要把数据保存到数据库中,我们使用InputStream属性,它用来初始化流来读取我们的数据。同时,我们使用ContentLength来读取文件大小,ContentType读取文件类型。然后创建byte数组,把文件流保存进该数组,然后保存到数据库即可。

下面就是完整的代码【CS版本】UploadFile.aspx:

<% @Page Language=""C#"" %>
<% @Import Namespace=""System.IO"" %>
<% @ Import Namespace=""System.Data"" %>
<% @ Import Namespace=""System.Data.SqlClient"" %>

<script runat=""server"">
public void UploadBtn_Click (Object sender, EventArgs e){

//得到提交的文件
Stream fileDataStream = MyFile.PostedFile.InputStream;

//得到文件大小
int fileLength = MyFile.PostedFile.ContentLength;

//创建数组
byte[] fileData = new byte[fileLength];

//把文件流填充到数组
fileDataStream.Read(fileData,0,fileLength);

//得到文件名字
string fileTitle = MyFileName.Value;

//得到文件类型
string fileType = MyFile.PostedFile.ContentType;

//构建数据库连接,SQL语句,创建参数
SqlConnection connection = new SqlConnection(""Server=.;uid=sa;pwd=;Database=TestUploadFile"");
SqlCommand command = new SqlCommand (""INSERT INTO TestFiles (MyFileName,MyFile,FileType)"" +
""VALUES (@MyFileName,@MyFile,@FileType)"", connection);

SqlParameter paramTitle = new SqlParameter (""@MyFileName"", SqlDbType.VarChar,35);
paramTitle.Value = fileTitle;
command.Parameters.Add(paramTitle);

SqlParameter paramData = new SqlParameter (""@MyFile"", SqlDbType.Image);
paramData.Value = fileData;
command.Parameters.Add(paramData);

SqlParameter paramType = new SqlParameter (""@FileType"", SqlDbType.VarChar,25);
paramType.Value = fileType;
command.Parameters.Add(paramType);

//打开连接,执行查询
connection.Open();
command.ExecuteNonQuery();
connection.Close();

Message.Text=""你的文件已经成功上载"";
MyFileName.Value = """";
}
</script>
<hr>
<asp:label id=""Message"" Text=""选择文件和文件名字:"" runat=""server""/>
<hr>
<form method=""post"" enctype=""multipart/form-data"" runat=""server"">
<b>文件名字:</b><input id=""MyFileName"" type=""text"" runat=""server"">
<P>
<b>文件:</b><input id=""MyFile"" type=""file"" runat=""server"">
<br><br>
<input type=submit value=""开始上传"" OnServerclick=""UploadBtn_Click"" runat=""server"">
</form>

一旦我们上载成功,我们可以对文件进行浏览:只需要设置页面的MIME类型,然后用Response对象的BinaryWrite()进行输出。

ShowUploadFile.aspx

<% @Page Language=""C#"" %>
<% @Import Namespace=""System.IO"" %>
<% @ Import Namespace=""System.Data"" %>
<% @ Import Namespace=""System.Data.SqlClient"" %>
<script runat=""server"">
private void Page_Load(Object sender, EventArgs e) {
string sql=""SELECT * FROM TestFiles"";
SqlConnection connection = new SqlConnection(""Server=.;uid=sa;pwd=;Database=TestUploadFile"");
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
FileList.DataSource = command.ExecuteReader();
FileList.DataBind();
connection.Close();
}
</script>

<form runat=""server"">
<asp:DataGrid id=""FileList"" runat=""server""
BorderColor=""orange"" BorderWidth=""2"" CellPadding=""4""
AutoGenerateColumns=""false"" ShowHeader=""true"" Align=""center"">
<HeaderStyle BorderColor=""White"" BackColor=""black"" ForeColor=""White""
Font-Bold=""True"" Font-Size=""9"" HorizontalAlign=""Center""/>
<Columns>
<asp:TemplateColumn HeaderText=""文件名字"">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, ""MyFileName"") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText=""类型"">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, ""FileType"") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn HeaderText=""查看"">
<ItemTemplate>
<b>
<a href='ShowFile.aspx?ID=<%# DataBinder.Eval(Container.DataItem, ""ID"") %>'>查看文件</a>
</b>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>

ShowFile.aspx

<% @Page Language=""C#"" %>
<% @Import Namespace=""System.IO"" %>
<% @ Import Namespace=""System.Data"" %>
<% @ Import Namespace=""System.Data.SqlClient"" %>
<script runat=""server"">
private void Page_Load(Object sender, EventArgs e) {
string sql=""SELECT * FROM TestFiles WHERE ID = '"" + Request.QueryString[""ID""] + ""'"";
SqlConnection connection = new SqlConnection(""Server=.;uid=sa;pwd=;Database=TestUploadFile"");
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read()){
Response.Clear();
Response.AddHeader(""Content-Type"",dr[""FileType""].ToString());
Response.BinaryWrite((byte[])dr[""MyFile""]);
}
dr.Close();
connection.Close();
}
</script>

另外需要注意的是:对exe,zip文件等还要进一步进行处理,以直接进行下载。

Macosx 2005-12-28
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/topic/4208/4208542.xml?temp=.9687921

from programming .net
读一个图片
MemoryStream stream = new MemoryStream ();
SqlConnection conn = new SqlConnection
("server=localhost;database=pubs;uid=sa;pwd=");

try {
conn.Open ();
SqlCommand cmd = new SqlCommand
("select logo from pub_info where pub_id='0736'", conn);
byte[] blob = (byte[]) cmd.ExecuteScalar ();
stream.Write (blob, 0, blob.Length);
Bitmap bitmap = new Bitmap (stream);
// TODO: Use the bitmap
bitmap.Dispose ();
}
catch (SqlException ex) {
// TODO: Handle the exception
}
finally {
stream.Close ();
conn.Close ();
}

写入
FileStream stream = new FileStream ("Logo.jpg", FileMode.Open);
byte[] blob = new byte[stream.Length];
stream.Read (blob, 0, (int) stream.Length);
stream.Close ();
SqlConnection conn = new SqlConnection
("server=localhost;database=pubs;uid=sa;pwd=");

try {
conn.Open ();
SqlCommand cmd = new SqlCommand
("insert into pub_info (pub_id, logo) values ('9937', @logo)",
conn);
cmd.Parameters.Add ("@logo", blob);
cmd.ExecuteNonQuery ();
}
catch (SqlException ex) {
// TODO: Handle the exception
}
finally {
conn.Close ();
}

110,578

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧