Add images to the database with ASP.NET

xiaoxiao2021-04-07  356

Sufficient condition for inserting images

Before we start upload, there are two important things we need to do:

#Form Tag ENCTYPE attribute should be set to encType = "Multipart / Form-Data"

# Need a form to make the user choose the file they want to upload, and we need to import the system.io namespace to process the flow object.

Apply the above three points to the ASPX page. At the same time, we need to prepare SQL Server.

# Require at least a table of fields with a picture type

# If we have another field of variable character type to store the picture type, it will be better.

Now we have a SQL table (including a field of an image data type), as well as the tag. Of course we have to prepare the Submit button so that the user is submitted after the image is selected. In the onclick event of this button, we need to read the contents of the selected image, then store it in the table. Then let's take a look at this onclick event.

The code of the onclick event of the submit button:

Dim Intimagesize As Int64

DIM STRIMAGETYPE AS STRING

DIM imageStream As Stream

'Gets the size of the image

Intimagesize = personimage.postedfile.contentLength

'Gets the Image Type

StrimageType = personimage.postedfile.contenttype

'Reads the Image

Imagestream = personimage.postedfile.inputStream

DIM imageContent (intImageSize) AS BYTE

DIM INTSTATUS AS INTEGER

IntStatus = images (ImageContent, 0, IntimageSize)

'Create Instance of Connection and Command Object

DIM MyConnection As New SqlConnection (ConfigurationSttings.AppSettings ("Connectionstring"))

DIM MyCommand As New SqlCommand ("sp_person_isp", myconnection)

'Mark The Command as a Sproc

Mycommand.commandtype = commandtype.storedprocedure

'Add Parameters to Sproc

Dim prmpersonImage as new Sqlparameter ("@ personimage", sqldbtype.image)

PRMPERSONIMAGE.VALUE = ImageContent

Mycommand.Parameters.Add (prmpersonimage)

Dim prmpersonimageType As New Sqlparameter ("@ personimageType", Sqldbtype.varchar, 255)

PRMPERSONIMAGETYPE.VALUE = STRIMAGETYPE

Mycommand.Parameters.Add (prmpersonimageType)

Try

myconnection.open () myCommand.executenonQuery ()

MyConnection.Close ()

Response.write ("New Person SuccessFully Added!")

Catch Sqlexc as Sqlexception

Response.write ("INSERT FAILED. Error Details Are:" & Sqlexc.toString ())

END TRY

How is this working?

PersonImage is an object of the HTMLInputFile control. First, you need to get the size of the picture, you can use the following code:

Intimagesize = personimage.postedfile.contentLength

Then return to the type of image Use the ContentYpe property. Finally, it is also the most important thing to get image stream, which can be implemented in the following code:

Imagestream = personimage.postedfile.inputStream

We need a byte array to store image content. Reading the entire image can be implemented using the READ method of the Stream object. The read (in Byte [] buffer, int off version is three parameters. [About the read method can be found .NET Frameworksdk] They are:

Buffer

Byte arrays. When this method returns, the buffer contains the specified character array, and the value between the array OFFSET and the OFFSET COUNT is replaced by the byte read from the current source.

Offset

The byte offset from zero starts from the buffer starts to store data read from the current stream from here.

count

The number of bytes to be read from the current stream.

This read method implements the following code:

IntStatus = images (ImageContent, 0, IntimageSize)

.

Now, we have read the content of the entire picture, the next step, we have to store these contents into the SQL table. We will use the stored procedure to complete the inserted image type and the image content to the SQL table. If you browse the above code, you will find that we use the data type of SqldbType.Image (DataType). OK, complete this, we also put the picture into the SQLServer.

SQL Server provides a special data type: Image, which is a type containing binary data. This example will show you how to put text or photos in the database. In this article we have to see how to store and read images in SQL Server.

1. Create a table:

Create a table of such a structure in SQL Server:

Column name type

ID Integer Primary Key ID

Imgtitle Varchar (50) Title

IMGTYPE VARCHAR (50) Picture Type. ASP.NET To identify type

IMGDATA image is used to store binary data

2, store pictures to the SQL Server database

In order to be stored in the table, you first go upload them on your web server, you can develop a web form, which is used to enter the image in the TextBox Web Control in your web server. Set your ENCTYPE attribute to: MyLtipart / Formdata.

Stream IMGDataStream = file1.postedfile.inputstream;

INT IMGDATALEN = file1.postedfile.contentLength; string emgtype = file1.postedfile.contentType;

String emgtitle = textbox1.text;

Byte [] IMGData = New byte [IMGDATALEN];

INT n = imgdatathastream.read (IMGDATA, 0, IMGDATALEN);

String connStr = (NameValueCollection) Context.getConfig ("appsettings")) ["connStr"];

SqlConnection Connection = New SqlConnection (connStr);

Sqlcommand command = new SQLCOMMAND

("INSERT IMAGTORE (Imgtitle, ImgType, IMGDATA)

VALUES (@Imgtitle, @ imgtype, @ imgdata) ", connection);

Sqlparameter paramtitle = new sqlparameter

("@Imgtitle", SqldbType.varchar, 50);

Paramtitle.Value = imgtitle;

Command.Parameters.add (paramtitle);

Sqlparameter paramdata = new sqlparameter ("@imgdata", sqldbtype.image);

Paramdata.value = IMGDATA;

Command.Parameters.Add (paramdata);

SQLParameter Paramtype = New Sqlparameter ("@ImgType", SqldbType.varchar, 50);

ParamType.Value = ImgType;

Command.Parameters.Add (paramtype);

Connection.open ();

INT NumrowSaffected = Command.executenonQuery ();

Connection.Close ();

3. Restore read from the database

Let us now read the data we put into the data from SQL Server! We will output pictures to your browser, you can also store it to your location.

Private Void Page_Load (Object Sender, System.EventArgs E)

{

String IMGID = Request.QueryString ["IMGID"];

String connStr = ((NameValueCollection)

Context.getConfig ("appsettings")) ["connStr"];

String SQL = "SELECT IMGDATA, IMGTYPE FROM Image" WHERE ID = " IMGID;

SqlConnection Connection = New SqlConnection (connStr);

Sqlcommand command = new SQLCOMMAND (SQL, Connection);

Connection.open ();

SqlDataReader Dr = Command.executeRead (); if (Dr.READ ())

{

Response.ContentType = DR ["iMgType"]. TOSTRING ();

Response.binaryWrite ((byte []) DR ["IMGDATA"]);

}

Connection.Close ();

}

Note that Response.BinaryWrite is not response.write.

Upload file to Access database

Image2access.aspx.cs

Using system;

Using system.collections;

Using system.componentmodel;

Using system.data;

Using system.data.oledb;

Using system.drawing;

Using system.Web;

Using system.io;

Using system.Web.SessionState;

Using system.Web.ui;

Using system.Web.ui.webcontrols;

Using system.Web.ui.htmlcontrols;

Namespace Emeng.exam

{

///

/// image2access's summary description.

///

Public class image2access: system.web.ui.page

{

protected system.web.ui.htmlcontrols.htmlinputtext myfilename;

Protected system.Web.ui.htmlcontrols.htmlinputfile myfile;

Protected system.web.ui.htmlcontrols.htmlinputbutton submit1;

Protected system.Web.ui.WebControls.DataGrid DG_PERSONS;

Private Void Page_Load (Object Sender, System.EventArgs E)

{

/ / Place the user code here to initialize the page

Bindgrid ();

}

Private void bindgrid ()

{

String strcn = "provider = microsoft.jet.Oledb.4.0; data source =" server.mappath ("image2access.mdb");

OLEDBCONNECTION MyConnection = New OLEDBCONNECTION (STRCNN);

OLEDBCommand mycommand = new oledbcommand ("Select * from person", myconnection);

Mycommand.commandtype = commandtype.text;

Try

{

MyConnection.open ();

DG_PERSONS.DataSource = mycommand.executeReader (Commandbehavior.CloseConne);

DG_PERSONS.DATABIND ();

}

Catch (OLEDBEXCEPTION SQLEXC)

{

Response.write ("Errors when extracting data:" SQLEXC.TOString ());

}

}

protected string formaturl (Object Strargument)

{

RETURN "Readimage.aspx? id =" strargument.toString ();

#Region web form designer generated code

Override protected void oninit (Eventargs E)

{

//

// Codegen: This call is necessary for the ASP.NET Web Form Designer.

//

InitializationComponent ();

Base.onit (E);

}

///

/// Designer supports the required method - do not use the code editor to modify

/// This method is content.

///

Private vidinitiRizeComponent ()

{

This.Submit1.ServerClick = new system.EventHandler (this.submit1_serverclick);

This.Load = New System.EventHandler (this.page_load);

}

#ndregion

Private void submit1_serverclick (Object Sender, System.Eventargs E)

{

// get the file submitted

Stream FileDataStream = myfile.postedfile.inputstream;

// Get the file size

INT filelength = myfile.postedfile.contentLength;

// Create an array

Byte [] fileData = new byte [filength ";

// Pack the file stream to an array

FileDataStream.read (FileData, 0, FileLength);

// Get the file name

String filetitle = myfilename.value;

// Get file type

String filetype = myfile.postedfile.contentType;

// Build a database connection, SQL statement, create parameters

String strcn = "provider = microsoft.jet.Oledb.4.0; data source =" server.mappath ("image2access.mdb");

OLEDBCONNECTION MyConnection = New OLEDBCONNECTION (STRCNN);

OleDbCommand command = new OleDbCommand ( "INSERT INTO Person (PersonName, PersonEmail, PersonSex, PersonImageType, PersonImage)" "VALUES (@ PersonName, @ PersonEmail, @ PersonSex, @ PersonImageType, @ PersonImage)", myConnection);

System.Data.Oledb.oledbParameter ParampersonName = New OledbParameter ("@ personname", System.Data.Oledb.oledbtype.varchar, 50);

ParampersonName.Value = filetitle; command.parameters.add (parampersonname);

System.Data.oledb.oledbParameter Parampersonemail = New OledbParameter ("@ personmail", system.data.oledb.oledbtype.varchar, 50); parampersonemail.value = "

Mengxianhui@dotnet.aspx.cc ";

Command.Parameters.Add (parampersonemail);

System.data.oledb.oledbParameter Parampersonsex = New OLEDBPARETER ("@ parampersonsex", system.data.oledb.oledbtype.varchar, 50);

paramPersonSex.Value = "M"; command.Parameters.Add (paramPersonSex); System.Data.OleDb.OleDbParameter paramPersonImageType = new OleDbParameter ( "@ PersonImageType", System.Data.OleDb.OleDbType.VarChar, 50);

ParampersonImageType.Value = filetype;

Command.Parameters.Add (parampersonimageType);

System.Data.oledb.oledbParameter ParampersonImage = New OledbParameter ("@ personimage", System.Data.Oledb.oledbtype.binary);

ParampersonImage.Value = filedata;

Command.Parameters.Add (parampersonImage);

// Open the connection, execute the query

MyConnection.open ();

Command.executenonQuery ();

MyConnection.Close ();

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-132428.html

New Post(0)