Author: Muzi http://blog.9cbs.net/derny/ first create a table that contains self-image segment and type and type of each image vnanchar
Webform1.aspx
! <% @ Page language = "c #" Codebehind = "WebForm1.aspx.cs" AutoEventWireup = "false" Inherits = "ReadAndWritePicFromDB.WebForm1"%>
Webform1.aspx.cs
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls Using system.web.ui.htmlcontrols; using system.io; using system.data.sqlclient; Namespace ReadanDwritePicFromDB {///
// Get file name private string getFile () {httppostedfile file = file1.postedfile; filename = file.filename;
Return filename;}
// Read file content private bote [] readfile () {filestream file = file.openread (getfile ()); byte [] content = new byte [file.length]; file.read (content, 0, content.length); ref- File.close (); Return Content;}
// Connect the database private void connectiondb () {string connStr = "initial catalog =; data source =; user ID =; password =;"; conn = new sqlconnection (conn.open ();
// Write a picture into the database private void writeImage () {sqlcommand comm = conn.createCommand (); comm.commandtext = "INTO images (Image, @ type)"; comm.comMandType = COMM.COMMANDTYPE = Commandtype.text; sqlparameter param = comm.parameters.add ("@ image", sqldbtype.image); param.value = readfile (); param = comm.Parameters.add ("@ type", sqldbtype.nvarchar); param .Value = getContentType (New fileinfo (filename) .extension.remove (0, 1)); if (Comm.ExecutenonQuery () == 1) Response.write ("Successful"); Else Response.write ("fail") Conn.close ();
/ / Get the compact name of the picture private string getContentType (String Extension) {String Type = "
IF (extension.equals ("jpg") || extension.equals ("jpg")) TYPE = "JPEG"; else type = extension;
Return "Image /" Type;}
// Read the picture from the database private void readimage () {sqlcommand comm = conn.createCommand (); comm.commandtext = "select image, type from images"; comm.commandtype = commandtype.text ;. COMMA.TEXT;
SqlDataReader Reader = Comm.executeReader (); while (Reader.Read ()) {response.contentType = Reader ["type"]. TOSTRING (); // Read and write Type must set otherwise the browser will be treated as a text Output Response .BinaryWrite ((byte []) reader ["image"]); // picture data}
Response.write ("Successful"); response.end ();
Conn.close ();} #Region Web Form Designer Generated Code Override Protected Void OnNit (Eventargs E) {// // Codegen: This call is required for the ASP.NET Web Form Designer. // InitializeComponent (); base.onit (e);} ///
Private void button1_click (object sender, system.eventargs e) {WriteImage ();
Private void button2_click (object sender, system.eventargs e) {Try {readimage ();} catch (exception ep) {conn.close (); response.end ();}}}}