The correct method for inserting images into the database and reading them using Asp.net

Source: Internet
Author: User
This article is written because I saw the previous article on the csdn homepage named "retrieving (retrieve) images from sqlserver in ASP. NET ". Article . The error is not mentioned because the method can indeed read the image from the database and display it in the browser. Code The intent cannot be fully implemented. The author also seems to have a thorough understanding of the HTTP protocol and the process in which the browser processes HTTP data.

1. How to make an error

The methods mentioned in this article are as follows:

Public sub page_load (sender as object, e as eventargs)
Dim myconnection as new sqlconnection (configurationsettings. etettings ("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, programmers want to output the images stored in the personimage field of all records in the person table to the browser at one time, in addition, if the output is successful, the "person info successfully retrieved!" is printed under the output image!" Information. However, in fact, the above Code only outputs the image in the first record correctly. For the browser, an HTTP request is used to obtain an object (HTML or image), so the output of the above Code will be used as a file (type based on response. contenttype = mydatareader. items ("personimagetype") are processed by the browser. If the HTTP type is image/JPEG, the browser uses the corresponding image parsing function to parse the image file. Therefore, the display result of the above Code can only be the image of the first record personimage field. The output image data recorded later will become the redundant data of the first image (This point is universal, but not absolute, depending on the image format ), the following "person info successfully retrieved!" Because the information is already encoded in the image file.

2. correct practices

A. input images to the database. The following is a code snippet that inputs images to the database: (complete demo)ProgramSee 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 = "insert into images (image, contenttype) values (@ 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 ("successfully insert image into database! ");

}

Else

{

MessageBox. Show ("failed to insert image into database ");

}

Conn. Close ();

B. code snippets read from images in the database: (for the complete demo program, see appendix 2)

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 the page_load event. Two points of attention should be paid to the data image:

1. Set the correct contenttype (Content-Type in HTTP). The Content-Type format of an image is generally image/*, for example, JPEG is image/JPEG and BMP is image/BMP.

2. Only one image binary stream is output. The page_load event in Asp.net is triggered before the page output. Therefore, the image output can be carried out in this event to directly operate the reponse object, avoid outputting external information irrelevant to the image (additional second image or text ). After the binary stream of the image is output, use the response. End () method to end the HTTP Response in time to avoid the extra information on the page being output to the client by the Asp.net engine by default.

I hope this article will serve as an example! Pai_^

Appendix 1:

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;

/// <Summary>

/// Required designer variable.

/// </Summary>

Private system. componentmodel. Container components = NULL;

Public mainform ()

{

//

// Required for Windows Form Designer support

//

Initializecomponent ();

//

// Todo: add Any constructor code after initializecomponent call

//

}

/// <Summary>

/// Clean up any resources being used.

/// </Summary>

Protected override void dispose (bool disposing)

{

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

# Region windows Form Designer generated code

/// <Summary>

/// Required method for designer support-do not modify

/// The contents of this method with the code editor.

/// </Summary>

Private void initializecomponent ()

{

This. openfiledlg = new system. Windows. Forms. openfiledialog ();

This. filepath = new system. Windows. Forms. Textbox ();

This. browsebutton = new system. Windows. Forms. Button ();

This. insertbutton = new system. Windows. Forms. Button ();

This. suspendlayout ();

//

// Openfiledlg

//

This. openfiledlg. defaultext = "*. jpg; *. gif; *. BMP; *. PNG ";

This. openfiledlg. Filter = "image files | *. jpg; *. gif; *. BMP; *. PNG | all files | *.*";

//

// 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. Controls. 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 );

}

# Endregion

/// <Summary>

/// The main entry point for the application.

/// </Summary>

[Stathread]

Static void main ()

{

Application. Run (New mainform ());

}

Private void browsebutton_click (Object sender, system. eventargs E)

{

If (openfiledlg. showdialog () = dialogresult. OK)

{

Filepath. Text = 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;

Using system. Web. UI. webcontrols;

Using system. Web. UI. htmlcontrols;

Namespace ReadImage

{

/// <Summary>

/// Summary description for ReadImage.

/// </Summary>

Public class ReadImage: system. Web. UI. Page

{

Private void page_load (Object sender, system. eventargs E)

{

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. Write ("aaaaaa ");

Response. End ();

Conn. Close ();

}

Catch

{

Response. End ();

}

}

# Region web form designer generated code

Override protected void oninit (eventargs E)

{

//

// Codegen: This call is required by the ASP. NET web form designer.

//

Initializecomponent ();

Base. oninit (E );

}

/// <Summary>

/// Required method for designer support-do not modify

/// The contents of this method with the code editor.

/// </Summary>

Private void initializecomponent ()

{

This. Load + = new system. eventhandler (this. page_load );

}

# Endregion

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.