When we have a large number of pictures or pictures are larger, our usual practice may be to save the image path, but also do not rule out the need to store the image directly into the database, it is necessary to save the image to the database. This article I will introduce to you:
- How to save a picture to a database by using the FileUpload control
- How to export a picture from a database via the button control
The steps are as follows:
Save picture to Database
First step: first create a table named "Images" in the database with the following code:
CREATE TABLE Images ( varchar (primarykeyvarchar( (+), varbinary(max datetime )
You can see that this table stores the contents: the registration number of the picture, the filename, the file 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
Of course you can also choose to enter this code directly in the CONVERSION.APSX file:
File Number<asp:textbox id="Txtrollno"runat="Server"></asp:textbox><br/>Select File<asp:fileupload id="FileUpload1"runat="Server"/><BR/><asp:button id="Button1"runat="Server"Text="Upload"onclick="Button1_Click"/>
Fourth Step: Once 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; using
You then write code within button1_click, convert the picture to a binary stream, and save it to the database through an SQL statement.
The code is as follows:
protected voidButton1_Click (Objectsender, EventArgs e) { if(!fileupload1.hasfile) {Response.Write ("File not selected"); return; } Else { //create an object to access the uploaded file and get the uploaded fileHttppostedfile file =Fileupload1.postedfile; //get file name and extension for uploaded files stringfilename =Path.getfilename (FileUpload1.PostedFile.FileName); stringExtension =path.getextension (filename); //instantiate a byte array whose length equals the length of the uploaded file byte[] ImageType =New byte[File. ContentLength]; //reads the file data into a byte arrayFile. Inputstream.read (ImageType,0, file. ContentLength); //Determine image format if(Extension = =". jpg") || (Extension = =". PNG") || (Extension = =". gif") || (Extension = =". bmp")) { //Table Write Data using(SqlConnection connection =NewSqlConnection ("Data source=afod3-609221015;initial catalog=mydata;integrated security=true") {connection. Open (); SqlCommand cmd=NewSqlCommand (); Cmd. Connection=connection; stringCommandText ="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");return; } }
View Code
Run results
In this case, we can browse the folder to add images to be deposited:
File successfully imported
If you select a file that does not meet the criteria, the result is displayed:
To return to the database, you can see that the picture has been successfully added to the database:
Export pictures
Now we see how to export pictures from the database, here I will just use the button control, a brief overview.
First step: Create an empty Web site in Visual Studio named "Imagetobinary".
Second Step: Add a new page, named "Getimage.aspx". Drag and drop a button control on this page.
Step Three: double-click the button and go to "GetImage.aspx.cs" to add a namespace.
using System; using System.Configuration; using System.Data.SqlClient; using System.IO;
Write code in Button1_Click:
protected voidButton1_Click (Objectsender, EventArgs e) { stringsconn = configurationmanager.appsettings["ConnectionString"]; SqlConnection objconn=NewSqlConnection (sconn); objConn.Open (); stringsql ="SELECT * from Images"; SqlCommand cmd=NewSqlCommand (SQL, objconn); SqlDataReader Dr=cmd. ExecuteReader (); while(Dr. Read ()) {byte[] bytes = (byte[]) dr["img"]; FileStream FS=NewFileStream (@"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
Operation Result:
Click "Export":
Open 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 into the database
Thanks for browsing!
Asp. NET database how to access pictures