ASP. NET database image access method,

Source: Internet
Author: User

ASP. NET database image access method,

When we have a large number of images or images, our common practice may be to save the image path, but we do not rule out the need to store the images directly to the database, in this case, you need to save the image to the database. This article will introduce you:

How to passFileUpLoad ControlSave images to the database
How to passButton ControlExport images from a database

The procedure is as follows:

Save images to the database

Step 1:First, create a table named "Images" in the database. The Code is as follows:

CREATE TABLE Images( Roll_no varchar(12) primary key,Name_File varchar(100),Extension varchar(100) , img varbinary(max) ,Img_date datetime ) 

You can see that this table stores the following content: the registration number, file name, file extension, binary data, and upload time of the image.

Step 2:Open Visual Studio and create an empty website named "ImageToBinary ".

Step 3:Add a new page named "Conversion. aspx"

On this page, we drag the TextBox, FileUpload, And Button controls.

Interface

Of course, you can also directly input this code string in the Conversion. apsx file:

File No. <asp: TextBox ID = "txtrollno" runat = "server"> </asp: TextBox> <br/> select a file <asp: fileUpload ID = "FileUpload1" runat = "server"/> <br/> <asp: button ID = "Button1" runat = "server" Text = "Upload" OnClick = "button#click"/>

Step 4:After adding the control, double-click the Button to enter the Conversion. apxs. cs file and add the following namespace:

using System;using System.Data;using System.Data.SqlClient;using System.IO;using System.Web; 

Then, write code in button#click to convert the image into a binary stream and save it to the database using SQL statements.

The Code is as follows:

Protected void button#click (object sender, EventArgs e) {if (! FileUpload1.HasFile) {Response. write ("file not selected"); return;} else {// create an object to access the uploaded file and obtain the uploaded file HttpPostedFile file = FileUpload1.PostedFile; // obtain the Object Name and extension string filename = Path. getFileName (FileUpload1.PostedFile. fileName); string extension = Path. getExtension (filename); // instantiate a byte array whose length is equal to the length of the uploaded object byte [] imagetype = new byte [file. contentLength]; // read the file data to the byte array file. inputStream. read (imagetype, 0, file. contentLength); // determine the image format if (extension = ". jpg ") | (extension = ". png ") | (extension = ". gif ") | (extension = ". bmp ") {// Data written to the table using (SqlConnection connection = new SqlConnection (" Data Source = AFOD3-609221015; Initial Catalog = MyData; Integrated Security = True ") {connection. open (); SqlCommand cmd = new SqlCommand (); cmd. connection = connection; string commandText = "Insert into Images values (@ image, @ Rollno, @ img, getdate ()"; cmd. commandText = commandText; cmd. commandType = CommandType. text; cmd. parameters. add ("@ image", SqlDbType. varBinary); cmd. parameters ["@ image"]. value = imagetype; cmd. parameters. add ("@ Rollno", SqlDbType. varChar); cmd. parameters ["@ Rollno"]. value = txtrollno. text; cmd. parameters. add ("@ img", SqlDbType. varChar); cmd. parameters ["@ img"]. value = txtrollno. text; cmd. executeNonQuery (); cmd. dispose (); connection. close (); Response. write ("imported successfully") ;}} else {Response. write ("Import failed"); return ;}}

Running result

In this case, you can browse the folder and add the image to be saved:

File imported

If a file that does not meet the conditions is selected, the result is displayed:

Return to the database. You can see that the image has been successfully added to the database:

Export Images

Now let's take a look at how to export images from the database. Here I will only use the Button control for a brief overview.

Step 1: Create an empty website in Visual Studio named "ImageToBinary ".

Step 2: Add a new page named "GetImage. aspx ". Drag and Drop a Button control on this page.

Step 3: double-click the Button to go to "GetImage. aspx. cs" and add the namespace.

using System;using System.Configuration;using System.Data.SqlClient;using System.IO;

Write code in button#click:

Protected void button#click (object sender, EventArgs e) {string sConn = ConfigurationManager. appSettings ["ConnectionString"]; SqlConnection objConn = new SqlConnection (sConn); objConn. open (); string SQL = "select * from Images"; SqlCommand cmd = new SqlCommand (SQL, objConn); SqlDataReader dr = cmd. executeReader (); while (dr. read () {byte [] bytes = (byte []) dr ["img"]; FileStream fs = new FileStream (@ "E: \ Images \ "+ dr [" roll_no "] + ". jpg ", FileMode. create, FileAccess. write); fs. write (bytes, 0, bytes. length); fs. flush (); fs. close ();} dr. close (); objConn. close (); Response. write ("exported ");}

Running result:

Click "Export ":

Open the specified folder, and the image is saved in it:

Finally, if necessary, you can refer to this article: How to save PDF, Word, and Excel files to the database

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.