Asp. NET database how to access pictures __ Database

Source: Internet
Author: User

When we have a large number of pictures or pictures larger, our usual practice may be to save the picture path, but also do not rule out the need to put the picture directly to the database, this time need to save the picture to the database. In this article, I'll show you how to save a picture to a database by using the FileUpload control how to export a picture from a database through a button control

The specific steps are as follows:

save pictures to database

The first step: first in the database to create a table named "Images", the code is as follows:

CREATE TABLE Images
(  
roll_no varchar () primary key,
name_file varchar (MB),
Extension varchar (100) ,  
img varbinary (max),
img_date datetime  
)  

You can see that this table stores the contents of the picture: the registration number, the filename, the file name extension, the binary data, and the upload time.

Step Two: then open visual Studio and create an empty Web site named "Imagetobinary".

Step Three: Add a new page, named "Conversion.aspx"

On this page we drag the three controls into the TextBox, FileUpload, button.

Interface as shown:

Of course you can also choose to enter this code directly in the CONVERSION.APSX file:

File serial number
<asp:textbox id= "Txtrollno" runat= "Server" >
</asp:TextBox>
<br/>

Select files
<asp:fileupload id= "FileUpload1" runat= "server"/> <br/> <asp:button id=

"Button1" runat = "Server"
text= "upload" onclick= "Button1_Click"/>

Step Fourth: after the control is added, double-click the button to enter the Conversion.apxs.cs file and add the following namespaces:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.IO;

Then write the code inside the button1_click, convert the picture into a binary stream and save it to the database through an SQL statement.

The code is as follows:

protected void Button1_Click (object sender, EventArgs e) {if (!
                Fileupload1.hasfile) {Response.Write ("no file selected");
            Return else {//Create an object to access the uploaded file, and get the uploaded files httppostedfile file = FileUpload

                1.PostedFile;  
                Gets the filename of the uploaded file and extension string filename = Path.getfilename (FileUpload1.PostedFile.FileName);  
               
                string extension = path.getextension (filename); Instantiates a byte array of length equal to the length of the uploaded file byte[] imagetype = new Byte[file.
                
                ContentLength]; Reads file data into a byte array, file. Inputstream.read (imagetype, 0, file. 

                ContentLength); Judge Picture format if ((Extension = = ". jpg") | | (Extension = = ". png") | | (Extension = = ". gif") | |
                (Extension = = ". bmp")) {//table write data 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 ("Import succeeded");
                } else {Response.Write ("Import Failed"); }
            }
View Code

Run the results as shown in figure:

We can then browse the folder to add the pictures that need to be saved:

File Import successfully

If you select a file that does not meet the criteria, the result is displayed:

Returning to the database, you can see that the picture has been successfully added to the database:

Export Pictures

Now let's see how to export a picture from a database, where I'll just use the button control for a brief overview.

First step: Create an empty Web site in Visual Studio named "Imagetobinary".

The second step: Add a new page, named "Getimage.aspx". Drag and drop a button control on this page.

Step Three: Double click the button, go to "GetImage.aspx.cs" and add the namespace.

Using System;
Using System.Configuration;
Using System.Data.SqlClient;
Using System.IO;

Write code within button1_click:

protected void Button1_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 ("successful export"); 


   
View Code

Run Result:

Click "Export":

Opens the specified folder, the picture has been saved in the inside:

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

Thanks for browsing.

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.