intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

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

Chia sẻ: Phan Thi Ngoc Giau | Ngày: | Loại File: PDF | Số trang:4

271
lượt xem
51
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Đầu tiên là phải thiết kế CSDL, ở đay tôi tạo 1 database mới có tên là Employee

Chủ đề:
Lưu

Nội dung Text: Lưu trữ và hiển thị hình ảnh trong Database - ASP.NET

  1. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Lưu trữ và hiển thị hình ảnh trong Database - ASP.NET Đầ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 CREATE DATABASE [Employee] 2 GO 3 USE [Employee] 4 GO 5 CREATE TABLE EmpDetails ( 6 empid int IDENTITY NOT NULL, 7 empname varchar(20), 8 empimg image 9 ) 10 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 Save Retrieve Images 3 4 5 6 7 8      9 10 11      12 13 14 16 17        &nbsp 19
  2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 20 21 22 23 24 25 26 27 28 29 B3: Viết sự kiện Click cho btnSubmit ? code 1 2 protected void btnSubmit_Click(object sender, EventArgs e) 3 { 4 SqlConnection connection = null; 5 try 6 { FileUpload img = (FileUpload)imgUpload; 7 Byte[] imgByte = null; 8 if (img.HasFile && img.PostedFile != null) 9 { 10 //To create a PostedFile 11 HttpPostedFile File = imgUpload.PostedFile; //Create byte Array with file len 12 imgByte = new Byte[File.ContentLength]; 13 //force the control to load data in array 14 File.InputStream.Read(imgByte, 0, File.ContentLength); 15 } // Insert the employee name and image into db 16 string conn = ConfigurationManager.ConnectionStrings 17 ["EmployeeConnString"].ConnectionString; 18 connection = new SqlConnection(conn); 19 20 connection.Open(); 21 string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY"; 22 SqlCommand cmd = new SqlCommand(sql, connection); 23 cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim()); 24 cmd.Parameters.AddWithValue("@eimg", imgByte); 25 int id = Convert.ToInt32(cmd.ExecuteScalar()); 26 lblResult.Text = String.Format("Employee ID is {0}", id); } 27 catch 28 { 29 lblResult.Text = "There was an error"; 30 } finally 31 { 32 connection.Close(); 33 } 34 35 } 36 37
  3. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 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 using System; 1 using System.Configuration; 2 using System.Web; 3 using System.IO; 4 using System.Data; using System.Data.SqlClient; 5 6 public class ShowImage : IHttpHandler 7 { 8 public void ProcessRequest(HttpContext context) 9 { 10 Int32 empno; if (context.Request.QueryString["id"] != null) 11 empno = Convert.ToInt32(context.Request.QueryString["id"]); 12 else 13 throw new ArgumentException("No parameter specified"); 14 15 context.Response.ContentType = "image/jpeg"; 16 Stream strm = ShowEmpImage(empno); byte[] buffer = new byte[4096]; 17 int byteSeq = strm.Read(buffer, 0, 4096); 18 19 while (byteSeq > 0) 20 { 21 context.Response.OutputStream.Write(buffer, 0, byteSeq); 22 byteSeq = strm.Read(buffer, 0, 4096); } 23 //context.Response.BinaryWrite(buffer); 24 } 25 26 public Stream ShowEmpImage(int empno) 27 { string conn = ConfigurationManager.ConnectionStrings 28 ["EmployeeConnString"].ConnectionString; 29 SqlConnection connection = new SqlConnection(conn); 30 string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID"; 31 SqlCommand cmd = new SqlCommand(sql,connection); 32 cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", empno); 33 connection.Open(); 34 object img = cmd.ExecuteScalar(); 35 try 36 { 37 return new MemoryStream((byte[])img); } 38 catch 39 { 40 return null; 41 } finally 42 { 43 connection.Close(); 44 } 45 } 46
  4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. public bool IsReusable 47 { 48 get 49 { 50 return false; 51 } } 52 53 54 } 55 56 57 58 59 60 61 62 63 64 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
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2