Source: Unknown Author: Unknown Recommended rating: Visits: 22
Write this image into the database and read the correct way to read with ASP.NET because the top page of 9CBS today's home page is called "Retrieve" in ASP.NET from SQLSERVER Search (RETRIEVE) Picture . Do not say that its mistake is because its method can indeed read the picture from the database and display it in the browser. Data process is known. 1, the following is a method of how this error mentioned article: Public Sub Page_Load (sender As Object, e As EventArgs) Dim myConnection As New SqlConnection (ConfigurationSettings.AppSettings ( "ConnectionString")) Dim myCommand As New SqlCommand ( "Select * from Person ", myConnection) Try myConnection.Open () Dim myDataReader as SqlDataReader myDataReader = myCommand.ExecuteReader (CommandBehavior.CloseConnection) Do While (myDataReader.Read ()) Response.ContentType = myDataReader.Item (" PersonImageType ") Response.BinaryWrite (myDataReader.Item ( "PersonImage")) Loop myConnection.Close () Response.Write ( "Person info successfully retrieved!") Catch SQLexc As SqlException Response.Write ( "Read Failed:" & SQLexc.ToString ()) End Try End Sub Obviously, the programmer wants to output the picture stored in the Personimage field in all records in the Person table to the browser, and print "Person" below the output picture in the output Info SuccessFully Retrieved! "information. However, in fact, the above code can only accurately output pictures in the first record. For the browser, an HTTP request obtains a file (HTML or image), so the output of the above code will be used as a file (type based on response.contenttype = myDataReader.Item ("PersonimageType") is handled by the browser. If the corresponding type of HTTP is image / JPEG, the browser uses the appropriate image resolution to parse this image file. Therefore, the display result of the above code can only be a picture of the first record of the Personimage field. The picture data of the back record output will be the extra data of the first picture (this point is universality, but not absolute, depending on the format of the picture), so that the "Person Info SuccessFully Retrieved!" Is naturally unable to This is shown because this information is already encoded in the image file.
2, the correct practice A, enter the image into the database, the following is a piece of code that enters the database to the database: (Full DEMO program See Appendix 1) FileStream Fs = file.openread (filepath.text); byte [] content = new byte [fs.Length]; fs.Read (content, 0, content.Length); fs.Close (); SqlConnection conn = new SqlConnection ( "Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = DatabaseImage; data source = (local) "); conn.open (); sqlcommand comm = conn.createCommand (); comm.commandtext =" IMGE, @Image, @contentType) "; Comm .CommandType = CommandType.Text; comm.Parameters.Add ( "@ image", SqlDbType.Image) .Value = content; comm.Parameters.Add ( "@ contentType", SqlDbType.NVarChar) .Value = getContentType (new FileInfo ( FilePath.Text) .extension.Remove (0, 1)); if (Comm.ExecutenonQuery () == 1) {MessageBox.show ("Success Insert Image Into Database!");} else {messagebox.show ("failed) To INSERT Image INTO DATABASE ");} conn.close (); b, the code snippet read out of the image in the database: (Full Demo program See Appendix II) Try {sqlconnection conn = new sqlConnection (" Integrated security = sspi; Persist security info = false; Initial Catalog = DatabaseImage; Data Source = (local) "); conn.Open (); SqlCommand comm = conn.CreateCommand (); comm.CommandText =" select * from Images where id = @ id "; comm.CommandType = CommandType .Text; Comm.Parameters.add ("@ ID", sqldbtype.bigint) .value = int.parse (Request ["ID"]); SqlDataReader Reader = Comm.ExecuteReader (); while (reader.read ()) {Response.contenttype = reader ["contenttype"]. TOSTRING (); response.binarywrite ((byte []) Reader ["image");} response.end (); conn.close ();
} catch {response.end ();} This code can be placed in page_load events, the two points should be noted in the data image: 1. Set the correct ContentType (Content-Type in HTTP), the Content-Type format of the image Generally IMAGE / *, such as JPEG is image / jpeg, BMP is image / BMP, etc. Second, only output a picture binary stream, the page_load event in the ASP.NET is triggered, so the output of the picture can be performed in this event, directly manipulate the reponse object, avoid output and the picture is not related to the picture (extra) The second picture or text). After the picture of the binary flow output, use the response.end () method to end the HTTP response, avoiding additional information in the page is output to the client by default by the ASP.NET engine.
I hope this article can play a role of tile jade! ^ _ ^ Appendix I: MainForm.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.IO; using System.Windows.Forms ; namespace InsertImageToDatabase {public class MainForm: System.Windows.Forms.Form {private System.Windows.Forms.OpenFileDialog openFileDlg; private System.Windows.Forms.TextBox filePath; private System.Windows.Forms.Button browseButton; private System.Windows .Forms.Button insertButton; ///
// // filepath // this.filepath.location = new system.drawing.point (16, 16); this.filepath.name = "filepath"; this.filepath.readonly = true; this.filepath.size = new System.drawing.size (168, 20); this.filepath.tabindex = 0; this.filepath.text = ""; /// Browsebutton // this.browsebutton.location = new system.drawing.point (200, 16); this.browseButton.Name = "browseButton"; this.browseButton.TabIndex = 1; this.browseButton.Text = "& Browse"; this.browseButton.Click = new System.EventHandler (this.browseButton_Click); // // insertButton // this.insertButton.Enabled = false; this.insertButton.Location = new System.Drawing.Point (200, 56); this.insertButton.Name = "insertButton"; this.insertButton.TabIndex = 2; this .insertButton.Text = "& Insert"; this.insertButton.Click = new System.EventHandler (this.insertButton_Click); // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); this .ClientSize = new system.drawing.size (292, 273); this.Controls.add (this.insertbutton); this.c ontrols.Add (this.browseButton); this.Controls.Add (this.filePath); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "MainForm"; this. Text = "INSERT Image to Database"; this.ResumeLayout (false);} #ENDREGON / //
openFileDlg.FileName; insertButton.Enabled = true;}} private void insertButton_Click (object sender, System.EventArgs e) {FileStream fs = File.OpenRead (filePath.Text); byte [] content = new byte [fs.Length]; fs.Read (content, 0, content.Length); fs.Close (); SqlConnection conn = new SqlConnection ( "Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = DatabaseImage; Data Source = (local)") ; conn.Open (); SqlCommand comm = conn.CreateCommand (); comm.CommandText = "insert into Images (Image, contentType) values (@image, @contentType)"; comm.CommandType = CommandType.Text; SqlParameter param = Comm.Parameters.Add ("@ image", sqldbtype.image); param.value = content; comm.parameters.add ("@ contenttype", sqldbtype.nvarchar) .value = getContentType (New fileInfo (filepath.text). Extension.Remove (0,1)); if (comm.ExecuteNonQuery () == 1) {MessageBox.Show ( "Successfully insert image into database!");} else {MessageBox.Show ( "Failed to insert image into database ");} conn.close ();} private string getContentType (String Extension) {string type = "jpeg"; if (extension == "jpg") {type = "jpeg";} else {type = extension;} return "image /" type;}}} Appendix 2: Readimage. aspx <% @ Page language = "c #" Codebehind = "ReadImage.aspx.cs" AutoEventWireup = "false" Inherits = "ReadImage.ReadImage"%> ReadImage.aspx.cs using System; using System.Collections; using System.ComponentModel Using system.data; using system.data.sqlclient; using system.drawing; using system.web; using system.web.sessionstate; using system.web.ui;