Tải bản đầy đủ (.pdf) (4 trang)

Lưu trữ và hiển thị hình ảnh trong Database doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (228.09 KB, 4 trang )

Lưu trữ và hiển thị hình ảnh trong Database - ASP.NET
 1

 2

 3

 4

 5

Đầu tiên là phải thiết kế CSDL, ở đay tôi tạo 1 database mới có tên là Employee
?
code
1
2
3
4
5
6
7
8
9
10
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,


empname varchar(20),
empimg image
)
B1: Tạo 1 Website mới và Import Namespace System.Data.SqlClient dùng để truy xuất CSDL
B2: Vào Design kéo tha 2 Label & 1 Textbox Control + 1 File Upload Control + 1 Image Control (để hiển thị hình
ảnh sau khi Upload)
?
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html xmlns="
<head runat="server">
<title>Save Retrieve Images</title>

</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp <asp:Label ID="lblResult" runat="server"
ForeColor="#0066FF"></asp:Label>
<br />
20
21
22
23
24
25
26
27
28
29

<hr />

<asp:Image ID="Image1" style="width:200px" Runat="server" />
</div>
</form>
</body>
</html>
B3: Viết sự kiện Click cho btnSubmit
?
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];

//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT
@@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}

}
38
B4: Bạn Click chuột phải vào Website tạo 1 file Generic Handler có tên là ShowImage.ashx chẳng hạn
?

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)

empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{

return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

public bool IsReusable
{
get
{
return false;
}
}


}
File này có nhiệm vụ Request thằng ID trên QueryString để SELECT trong bảng EmpDetail và lấy về trường
Image và gán nó vào 1 Stream có tên là ShowEmpImage. Từ Stream đó thì quá dễ để bạn Write ra file ảnh jpg
hoặc gif rùi
B5 Bước cuối cùng: trong sự kiện btnSubmit_Click (dòng trước Catch) bạn set lại thuộc tính ImageURL cho
Control Image1
?
code
1
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
Download Source Code tại đây.
Theo dotnetcurry

×