zoukankan
html css js c++ java
Asp.Net在SqlServer中的图片存取
在使用asp.net将图片上传并存入SqlServer中,然后从SqlServer中读取并显示出来
一,上传并存入sqlserver
数据库结构
create
table
test
{
id
identity
(
1
,
1
),
FImage
image
}
相关的存储过程
Create
proc
UpdateImage
(
@UpdateImage
Image
)
As
Insert
Into
test(FImage)
values
(
@UpdateImage
)
GO
在upphoto.aspx文件中添加如下:
<
input id
=
"UpPhoto" name
=
"UpPhoto" runat
=
"server" type
=
"
file
"
>
<
asp:Button id
=
"btnAdd" name
=
"btnAdd" runat
=
"server"
Text
=
"上传"
></
asp:Button
>
然后在后置代码文件upphoto.aspx.cs添加btnadd按钮的单击事件处理代码:
private void btnAdd_Click(object sender, System.EventArgs e)
{
//
获得图象并把图象转换为byte
[]
HttpPostedFile upPhoto
=
UpPhoto.PostedFile;
int
upPhotoLength
=
upPhoto.ContentLength;
byte
[]
PhotoArray
=
new Byte
[
upPhotoLength
]
;
Stream PhotoStream
=
upPhoto.InputStream;
PhotoStream.
Read
(PhotoArray,
0
,upPhotoLength);
//
连接数据库
SqlConnection conn
=
new SqlConnection();
conn.ConnectionString
=
"Data Source
=
localhost;
Database
=
test;
User
Id
=
sa;Pwd
=
sa";
SqlCommand cmd
=
new SqlCommand("UpdateImage",conn);
cmd.CommandType
=
CommandType.StoredProcedure;
cmd.Parameters.
Add
("
@UpdateImage
",SqlDbType.
Image
);
cmd.Parameters
[
"@UpdateImage"
]
.Value
=
PhotoArray;
//
如果你希望不使用存储过程来添加图片把上面四句代码改为:
//
string strSql
=
"
Insert
into
test(FImage)
values
(
@FImage
)";
//
SqlCommand cmd
=
new SqlCommand(strSql,conn);
//
cmd.Parameters.
Add
("
@FImage
",SqlDbType.
Image
);
//
cmd.Parameters
[
"@FImage"
]
.Value
=
PhotoArray;
conn.
open
();
cmd.ExecuteNonQuery();
conn.
Close
();
}
二,从sqlserver中读取并显示出来
在需要显示图片的地方添加如下代码:
<
asp:
image
id
=
"imgPhoto" runat
=
"server" ImageUrl
=
"ShowPhoto.aspx"
></
asp:
image
>
showphoto.aspx主体代码:
private void Page_Load(object sender, System.EventArgs e)
{
if
(!Page.IsPostBack)
{
SqlConnection conn
=
new SqlConnection()
conn.ConnectionString
=
"Data Source
=
localhost;
Database
=
test;
User
Id
=
sa;Pwd
=
sa";
string strSql
=
"
select
*
from
test
where
id
=
2
";
//
这里假设获取id为2的图片
SqlCommand cmd
=
new SqlCommand()
reader.
Read
();
Response.ContentType
=
"application
/
octet
-
stream";
Response.BinaryWrite((Byte
[]
)reader
[
"FImage"
]
);
Response.
End
();
reader.
Close
();
}
}
查看全文
相关阅读:
LRU算法实现 最近最久未使用
快速排序
redis 常用命令
实例:接口并发限流RateLimiter
Hadoop伪分布式安装
ssl免密登录(centos6)
Linux下安装jdk-7u67-linux-x64.rpm
Mosquitto安装和使用
MQTT linux centOS7 部署
CentOS更换yum源
原文地址:https://www.cnblogs.com/RuiLei/p/568741.html
最新文章
alibaba fastjson jsonarray转list
Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
myeclipse基础配置
myeclipse打开报integrity check error错误
redis服务安装及连接(转)
javabean转json,json转javabean,json字段首字母大写
POI判断excel文件版本
mysql 1103错误
mysql服务无法启动
大中台+小前台概念
热门文章
Zookeeper--Paxos算法的原理及过程透彻理解
Flume(一)Flume原理解析
@RestControllerAdvice作用及原理
深入理解Java枚举类型(enum)
注解原理
添加主机映射
开发FTP服务接口,对外提供接口服务
Tomcat中使用JNDI配置各种数据源
最短路径(二维矩阵)
返回数组中最长递增字符串
Copyright © 2011-2022 走看看